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



9 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!

  6. Buy Backlinks says:

    This is a good blog. Keep up all the work. I too love blogging and expressing my opinions. Thanks :)

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

  8. Shivam Patel says:

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

  9. Ashish says:

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

Leave a Reply

 
May 2012
M T W T F S S
« Dec    
 123456
78910111213
14151617181920
21222324252627
28293031  
Social Media
Get in Touch
contact[at]jigyasamakkar[dot]com