A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Wednesday, February 10, 2010

Rails, Time Zones and the current local time

Since version 2.1 it has been easy to handle user-specific time zones in Rails. Take a look at Railscast #106 for details.

Rails takes care of converting times in your models back and forth from local timezones and UTC in the database and it works great.

But I wanted to put the current local time at the bottom of each page, so that if they printed out the page they had a time stamp right there.

My server is set up to with UTC as its time zone and Rails picks up on that, such that if I simply print out Time.now I get it in UTC, regardless of having set Time.zone to 'US Pacific...', which is not what I want.

Because I'm not accessing the time from a database record, it doesn't apply the user specific conversion.

The way to do this is to add 'in_time_zone' which forces Time to use the current Time.zone.

Bottom Line:

To display the current time in a user's local time zone, use Time.now.in_time_zone




 

No comments:

Archive of Tips