Rails: Format a date time string taking care of the timezone
Today I had to fix a test on a CSV export having wrong dates.
Our Rails application has UTC as timezone, so dates in the database are in UTC, and we need to show dates in our timezone.
As example, we inserted an object in its table and the created_at is then 2012-12-18 11:33:00.
In order to format that date into '%d/%m/%Y %H:%M' I did the following:
Time.parse("2012-12-18 11:33:00").to_s(:legacy_datetime)
=> "18/12/2012 11:33"
Oops... The time is still in UTC. In order to fix that I found this:
Time.parse("2012-12-18 11:33:00 +0000").to_s(:legacy_datetime)
=> "18/12/2012 12:33"
Notice the appended " +0000" string to the date.
Written by Guillaume Hain
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#