Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Ago" date/time functions in Ruby/Rails

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?

like image 665
kapso Avatar asked Jul 19 '10 06:07

kapso


People also ask

How do I get yesterday's Date in Ruby?

You can just subtract 86400 from a Time object to get one day before. If you are using Rails, or have ActiveSupport included, you can replace 86400 with 1. days . If you're using a Date object, and not a Time object, just subtract 1 from it.

What is now () in Ruby?

Ruby | DateTime now() function DateTime#now() : now() is a DateTime class method which returns a DateTime object denoting the given calendar date. Return: DateTime object denoting the given calendar date.

How do I convert time in Ruby?

In your code above, simply replace d = DateTime. now with d = DateTime. new(2010,01,01, 10,00,00, Rational(-2, 24)). tt will now show the date d converted into your local timezone.


Video Answer


3 Answers

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.

like image 143
Toby Hede Avatar answered Oct 19 '22 01:10

Toby Hede


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

like image 13
Deepak Mahakale Avatar answered Oct 19 '22 03:10

Deepak Mahakale


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
like image 4
Dorian Avatar answered Oct 19 '22 01:10

Dorian