I am a web developer working with
SlideShare, Delhi. This is my Website.

Ruby on Rails views : Time ago in words for string time


07.27.10 Posted in Blog by admin

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”.



5 Responses to “Ruby on Rails views : Time ago in words for string time”

  1. Josefina Nylund says:

    Good one, accurate and interesting like hell.

  2. Finding the best CNA School says:

    It’s posts like this that keep me coming back and checking this site regularly, thanks for the info!

  3. veterinary technician says:

    What a great resource!

  4. Genial brief and this enter helped me alot in my college assignement. Say thank you you on your information.

  5. party supplies says:

    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!

Leave a Reply