1

Rails stores created_at and updated_at timestamps in UTC time.

But I am using these fields to filter and store (and do a lot of other stuff with the records) based on these fields, so it's important that when I call created_at and updated_at attributes, I get timestamps in my time zone.

As told by the following two SO questions, I can do that by configuring the time zone in the environment.rb file.

However, that's now working for me.

Because I am fetching the records from the database, based on created_at fields (which are in UTC) so naturally wrong ones are coming out, and then I am displaying them, so the dates are displayed in UTC, again, not what I want.

Is there a way to change in what time-zones the rails stores the dates?

OR

Is there a workaround for how I can achieve the database-fetching and displaying, without making a call to Rails object.created_at attribute?

Rails and timezone in created_at

Rails Time zone issue

Community
  • 1
  • 1
Saad Rehman Shah
  • 926
  • 2
  • 10
  • 28
  • I'm not sure I understand. The 'right way' to do this is for the records to be stored in UTC, then setting `Time.zone` in the cases you need it set to something else. – x1a4 May 08 '12 at 06:33

1 Answers1

0

I wonder why I even asked the question on this forum, because the workaround seemed to be pretty simple. But it did take me eight hours to reach it :)

1) While fetching records from the database and displaying them, I could simply do

select CONVERT_TZ(date) as date from table;

instead of doing

select date from table;

CONVERT_TZ() is a mysql specific function, so it worked for me. Not a universal solution though.

2) Secondly, when I had to fetch the records from a date range given in any other time-zone, I could do one of the two things.

One - I could replace [user-entered-date] 00:00:00 with [user-entered-date] 07:00:00 for the date-range's starting point and [user-entered-date] 59:59:59 with [user-entered-date + 1.day] 07:00:00 for the range's ending point. Note this would require me to use DateTime objects instead of using Date objects.

Two - In the where clause, I could do

CONVERT_TZ(registrations.created_at) <= [user/entered/date]

instead of

(registrations.created_at) <= [user/entered/date]
Saad Rehman Shah
  • 926
  • 2
  • 10
  • 28