Back

ruby中的日期操作(date time in ruby)

发布时间: 2015-06-02 07:21:00

2010年就因为这个耗费了一点时间。现在记下来。

strftime , strptime是关键。

下面的代码打印了两个时间之间的日期:

require 'date'
from = DateTime.strptime('2015-05-23', '%Y-%m-%d')
to = DateTime.strptime('2015-06-03', '%Y-%m-%d')
(from..to).each do |date|
  puts date.strftime('%Y-%m-%d')
end

# 结果:
2015-05-23
2015-05-24
2015-05-25
2015-05-26
2015-05-27
2015-05-28
2015-05-29
2015-05-30
2015-05-31
2015-06-01
2015-06-02

获取某个时间的 具体星期几:

DateTime.strptime(date, '%Y-%m-%d').wday

Back