"Ago" date/time functions in Ruby/Rails

Ruby on-RailsRubyDatetime

Ruby on-Rails Problem Overview


I was wondering if there's a way in Rails to calculate time stamp like - half a minute ago, 2 minute ago, 1 day ago etc. Something like twitter real time date stamp.

I want to know if Ruby/Rails has a built-in function for such date-time conversion?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can use:

10.minutes.ago
2.days.since

Or in your views you have the helpers:

distance_of_time_in_words(from_time, to_time)
time_ago_in_words(from_time)

Check the API for details and more options.

Solution 2 - Ruby on-Rails

You can use available methods to get the time in past or future using ago, since alias for from_now and many available methods

Time.current
#=> Tue, 20 Sep 2016 15:03:30 UTC +00:00

2.minutes.ago
#=> Tue, 20 Sep 2016 15:01:30 UTC +00:00

2.minutes.since
#=> Tue, 20 Sep 2016 15:05:30 UTC +00:00 

1.month.ago
#=> Sat, 20 Aug 2016 15:03:30 UTC +00:00

1.year.since
#=> Wed, 20 Sep 2017 15:03:30 UTC +00:00 

Check all the available methods in Time class

Solution 3 - Ruby on-Rails

distance_of_time_in_words:

from_time = Time.now

distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds

time_ago_in_words:

time_ago_in_words(3.minutes.from_now) # => 3 minutes
time_ago_in_words(3.minutes.ago) # => 3 minutes
time_ago_in_words(Time.now - 15.hours) # => about 15 hours

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkapsoView Question on Stackoverflow
Solution 1 - Ruby on-RailsToby HedeView Answer on Stackoverflow
Solution 2 - Ruby on-RailsDeepak MahakaleView Answer on Stackoverflow
Solution 3 - Ruby on-RailsDorianView Answer on Stackoverflow