Last Updated: February 25, 2016
·
1.087K
· zedtux

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.