nufonamed
nufonamed

Reputation: 3

Ruby datetime issue

i have date range

(DateTime.now.change({hour: 01}).to_datetime.to_i .. DateTime.tomorrow.change({hour: 23}).to_datetime.to_i).step(1.hour) do |date|
  p Time.at(date)
end

but it produce 4 more additional hours

(DateTime.now.change({hour: 01}).to_datetime.to_i .. DateTime.tomorrow.change({hour: 23}).to_datetime.to_i).step(1.hour) do |date|
 p Time.at(date)      
 end      
2018-04-20 01:00:00 +0300
2018-04-20 02:00:00 +0300
2018-04-20 03:00:00 +0300
2018-04-20 04:00:00 +0300
2018-04-20 05:00:00 +0300
2018-04-20 06:00:00 +0300
2018-04-20 07:00:00 +0300
2018-04-20 08:00:00 +0300
2018-04-20 09:00:00 +0300
2018-04-20 10:00:00 +0300
2018-04-20 11:00:00 +0300
2018-04-20 12:00:00 +0300
2018-04-20 13:00:00 +0300
2018-04-20 14:00:00 +0300
2018-04-20 15:00:00 +0300
2018-04-20 16:00:00 +0300
2018-04-20 17:00:00 +0300
2018-04-20 18:00:00 +0300
2018-04-20 19:00:00 +0300
2018-04-20 20:00:00 +0300
2018-04-20 21:00:00 +0300
2018-04-20 22:00:00 +0300
2018-04-20 23:00:00 +0300
2018-04-21 00:00:00 +0300
2018-04-21 01:00:00 +0300
2018-04-21 02:00:00 +0300
2018-04-21 03:00:00 +0300

What is wrong with my code?

ideally i want to set range from 01 to 23 h, maybe any other solution you can provide?

Upvotes: 0

Views: 87

Answers (2)

Imre Raudsepp
Imre Raudsepp

Reputation: 1198

Its because Time.at uses timezone what is +3h in your country http://api.rubyonrails.org/classes/Time.html#method-c-at_with_coercion

Upvotes: 2

Deepak Mahakale
Deepak Mahakale

Reputation: 23691

I think what you need is beginning_of_day and end_of_day

(Date.today.beginning_of_day.change(hour: 01).to_i..Date.today.end_of_day.to_i).step(1.hour) do |date|
  p Time.at(date)
end

This will return you

2018-04-20 01:00:00 +0300
2018-04-20 02:00:00 +0300
2018-04-20 03:00:00 +0300
2018-04-20 04:00:00 +0300
2018-04-20 05:00:00 +0300
2018-04-20 06:00:00 +0300
2018-04-20 07:00:00 +0300
2018-04-20 08:00:00 +0300
2018-04-20 09:00:00 +0300
2018-04-20 10:00:00 +0300
2018-04-20 11:00:00 +0300
2018-04-20 12:00:00 +0300
2018-04-20 13:00:00 +0300
2018-04-20 14:00:00 +0300
2018-04-20 15:00:00 +0300
2018-04-20 16:00:00 +0300
2018-04-20 17:00:00 +0300
2018-04-20 18:00:00 +0300
2018-04-20 19:00:00 +0300
2018-04-20 20:00:00 +0300
2018-04-20 21:00:00 +0300
2018-04-20 22:00:00 +0300
2018-04-20 23:00:00 +0300

Upvotes: 1

Related Questions