I want date part from an instance of ActiveSupport::TimeWithZone. I used to_date function for that but it returns date one day earlier.
For example, if datetime is 2012-04-11 09:05:00 UTC, and if I call to_date then it returns 2012-04-10 but 2012-04-11.
Also I am not using specific timezone (defaults to UTC)
The application is running on Ruby 1.8.7 and Rails 3.0.2
Can anyone please tell me why it gives wrong date? Also please suggest me if there is better way to get date (instance of Date) part from given DateTime (instance of ActiveSupport::TimeWithZone)
EDIT :
someone is also facing same issue here http://pastebin.com/sn8ExZiQ
NOTE : Time.zone returns 'UTC'
Thanks Jignesh. Here I am sharing your findings and solutions.
There may be some gem that is overriding
to_dateimplementation and it may be implemented incorrectly and this overridden version might be getting called.In my case the culprit was
ruby-unitsgemRoot Cause :
ruby-unitsgem included in the application’s GemfileProblem Analysis :
Gemfile
time.rb file (ruby-units gem codebase)
Lets say that current time in
UTCtime-zone isWed, 11 Apr 2012 10:12:17 UTC +00:00represented by aActiveSupport::TimeWithZoneinstance.
From the rails application when we execute
<TimeWithZone>.to_dateit returnsa date
2012-04-10which is incorrect.The culprit involved in above incorrect behavior is the implementation of
to_datemethodprovided by
ruby-unitsgemBelow is a sample program to demonstrate the above incorrect behaviour. The
to_datemethod is identical to one implemented byruby-unitsgem, except that an argument is added to the method namelydate_timeand theselfin the implementation is replaced by the argument‘date_time’.
Sample Ruby Program to confirm the findings above:
Output (date at the time of writing this was Wed,
11 Apr 2012 08:35:12 UTC +00:00):Solution:
ruby-unitsgem from theGemfileor load it after rails gemdatetime.to_date, usedatetime.to_s.to_date