I worked my way around an interesting information tidbit discovery yesterday. The use case seemed pretty simple and direct. I needed to display the “n hours ago” text in my view. I used the awesome view helper ‘time_ago_in_words’ to do that and it worked, well almost.
Here’s what I’m talking about:
In console,
time_string = "2010-07-21 11:52:31"
helper.time_ago_in_words(time_string) # => about 5 hours
The catch here is that the “5 hours” duration is incorrect. This was hardly 5 minutes ago! So, the problem here was in time zones.
By default,
time_string.to_time # => Wed Jul 21 11:52:31 UTC 2010
Notice the time zone offset. It has been set to “UTC” by default. But the original time zone of this string time was different. And the tricky part is, it was different for different environments. So how’d we get past this? Here’s the entire snippet:
def custom_time_ago_in_words(time_str)
time = time_str.to_time + (-Time.zone_offset(Time.now.zone))
"#{time_ago_in_words(time)} ago"
end
This essentially adjusts the time according to the server time zone and gives correct output as “5 minutes ago”.

Good one, accurate and interesting like hell.
It’s posts like this that keep me coming back and checking this site regularly, thanks for the info!
What a great resource!
Genial brief and this enter helped me alot in my college assignement. Say thank you you on your information.
Good blog! I actually love how it is easy on my eyes and the info are well written. I am wondering how I can be notified whenever a new post has been made. I have subscribed to your rss feed which should do the trick! Have a nice day!
This is a good blog. Keep up all the work. I too love blogging and expressing my opinions. Thanks
I really appreciate the way the website is laid out. I think it is great. If you dont care me asking what template is the blog? Thanks.
why not change the default timezone in application.rb (environment.rb for rails2):
config.time_zone = “Pacific Time (US & Canada)”
Also I couldn’t understand by what you meant by:
“And the tricky part is, it was different for different environments. “
@Shivam : “And the tricky part is, it was different for different environments. “
means that the people using that application were located in different time zones , so using a single time zone as default in environment.rb was not a feasible idea .
Thank you.