Reputation: 1156
In Ruby I am trying to convert a Date into a format that is usable by the HighCharts
JavaScript charting library. Odd thing is when I convert the Date to seconds it converts differently than when I convert a Time
to seconds and differently when I convert a DateTime
to seconds. Due to this difference in conversion the dates displayed on the Graph can be as much as 1 date behind.
I am sure this has something to do with Rails and how it handles conversion from UTC to Local. If someone could explain to me the details I would greatly appreciate it.
In my examples below I use the same date '2011/05/02' but the seconds come out to be different.
Examples:
Date.new(2011, 5, 2).to_time.to_i * 1000
=> 1304265600000
=> 05/01/2011
Time.utc(2011, 5, 2).to_i * 1000
=> 1304294400000
=> 05/02/2011
Date.new(2011, 5, 2).to_datetime.to_i * 1000
=> 1304294400000
=> 05/02/2011
Upvotes: 1
Views: 1015
Reputation: 397
ruby-1.9.2-p180 :106 > Time.utc(2011, 5, 2)
=> 2011-05-02 00:00:00 UTC
ruby-1.9.2-p180 :107 > Date.new(2011, 5, 2).to_time
=> 2011-05-02 00:00:00 +0300
Date.to_time generates Time with timezone. That's your difference. The quick fix/hack that popped instantly into my mind is:
Date.new(2011, 5, 2).to_time.utc.midnight
Edit: http://apidock.com/rails/Date/to_time
Date.new(2011, 5, 2).to_time(:utc)
Upvotes: 2