Thursday, April 15, 2010

Tip of the day: Keep the database timestamp and Time.now in sync

I stumbled across a situation when I have to schedule a job and I have to store today's weekday. I am also storing the schedule's created_at/ updated_at time in datetime format.

To store today's weekday, I said:
weekday = Time.now.wday
>> 4   #Thursday

When I stored the record
Schedule.first.created_at.wday
>> 3  #Wednesday

Why?

I dug in more and here are the facts.
We so say in environment.rb file:
config.time_zone = 'UTC'
But this applies to only the created_at/updated_at attributes and sets up the default timezone for the database and never applies to Time.now


So to keep Time.now in sync we have to set ENV['TZ'] in environment.rb file.


Again in console:
weekday = Time.now.wday
>> 3   #Wednesday


Schedule.first.created_at.wday
>> 3  #Wednesday

:)

2 comments:

Niranjan said...

That was a nice tip ! Thanks Gourav.

Gourav Tiwari said...

Well just an update, there is an alternative to do this:

You remove the ENV['TZ'} and use the following:

config.active_record.default_timezone = 'Eastern Time (US & Canada)'

config.time_zone = 'Eastern Time (US & Canada)'