我有一个start_dt和一个end_dt对象,类型为datetime。
我如何从start_dt循环,每次递增1天,直到我到达结束日期?
答案 0 :(得分:1)
您可以在upto
和downto
个对象上使用Date
和DateTime
方法:
start_dt = DateTime.parse('2018-01-01')
end_dt = DateTime.parse('2018-01-15')
start_dt.upto(end_dt) { |date| puts date }
2018-01-01T00:00:00+00:00
2018-01-02T00:00:00+00:00
2018-01-03T00:00:00+00:00
2018-01-04T00:00:00+00:00
2018-01-05T00:00:00+00:00
2018-01-06T00:00:00+00:00
2018-01-07T00:00:00+00:00
2018-01-08T00:00:00+00:00
2018-01-09T00:00:00+00:00
2018-01-10T00:00:00+00:00
2018-01-11T00:00:00+00:00
2018-01-12T00:00:00+00:00
2018-01-13T00:00:00+00:00
2018-01-14T00:00:00+00:00
2018-01-15T00:00:00+00:00
end_dt.downto(start_dt) { |date| puts date }
2018-01-15T00:00:00+00:00
2018-01-14T00:00:00+00:00
2018-01-13T00:00:00+00:00
2018-01-12T00:00:00+00:00
2018-01-11T00:00:00+00:00
2018-01-10T00:00:00+00:00
2018-01-09T00:00:00+00:00
2018-01-08T00:00:00+00:00
2018-01-07T00:00:00+00:00
2018-01-06T00:00:00+00:00
2018-01-05T00:00:00+00:00
2018-01-04T00:00:00+00:00
2018-01-03T00:00:00+00:00
2018-01-02T00:00:00+00:00
2018-01-01T00:00:00+00:00
答案 1 :(得分:0)
这个怎么样?
current_date = object.start_dt
end_date = object.end_dt
loop do
## do something
## (`:beginning_of_day` and `:end_of_day` may help you)
current_date += 1.day
break if current_date > end_date
end
答案 2 :(得分:0)
尝试以下
start_date = Time.now - 30.day
=> 2017-12-16 09:19:51 +gmt
end_date = Time.now
=> 2018-01-15 09:19:44 +gmt
start_date = Date.parse "#{start_date}"
end_date = Date.parse "#{end_date}"
date_count = (end_date - start_date).to_i
=> 30
<% (1..date_count).each do |i| %>
#Code to display using <%= i %> that you want to display
<% end %>
希望能提供帮助
答案 3 :(得分:0)
试试这些:
(DateTime.parse('2018-01-01')..DateTime.parse('2018-01-15')).each do |date|
puts date
end