John
John

Reputation: 1323

how to get time difference in minutes in rails for two date time fields?

i want to calculate time difference in minutes between two date_time fields.like created_at and updated_at kind of fields. i want the result like this updated_at - created_at = some minutes.

these times are present in time zone of INDIA. how can i do that in rails?

created = article.created_at
updated = article.updated_at

minutes = updated - created

Upvotes: 18

Views: 29223

Answers (5)

hqt
hqt

Reputation: 30284

The data type of ActiveRecord's columns created_at and updated_at is ActiveSupport::TimeWithZone. If you want to do the operation with DateTime, you need to convert it first

now = DateTime.now
creation_time = user.created_at.to_datetime        
diff_in_minutes = ((now - creation_time) * 24 * 60).to_i

You can test this easily in the Rails console, but for easier testing, you can convert it to seconds instead

diff_in_seconds = ((now - creation_time) * 24 * 60 * 60).to_i

Upvotes: 0

simo
simo

Reputation: 24600

looking at helper time_ago_in_words, we can say:

    from_time = from_time.to_time if from_time.respond_to?(:to_time)
    to_time = to_time.to_time if to_time.respond_to?(:to_time)
    #absolute distance:
    from_time, to_time = to_time, from_time if from_time > to_time
    distance_in_minutes = ((to_time - from_time)/60.0).round

Upvotes: 1

Doug
Doug

Reputation: 15533

This solution works for ActiveRecord models using TimeWithZone classes for created_at and updated_at.

created = article.created_at
updated = article.updated_at

minutes = (updated - created) / 1.minutes

Upvotes: 47

Pavan
Pavan

Reputation: 33542

As created_at and updated_at are of type DateTime, this should work.

created = article.created_at
updated = article.updated_at
minutes = ((updated - created) * 24 * 60).to_i

Explanation:

Subtracting two DateTimes returns the elapsed time in days. In the below example e-d will return (28807336643183/28800000000000). So to convert this into minutes, we need to multiply it by 24*60(As the day has 24 hours and each hour has 60 minutes)

Example(tested):

d = DateTime.now
 => Tue, 13 Jun 2017 10:21:59 +0530 
2.3.3 :003 > e = DateTime.now + 1.day
 => Wed, 14 Jun 2017 10:22:21 +0530
g = ((e-d) * 24 * 60).to_i
 => 1440

Upvotes: 19

ZainNazirButt
ZainNazirButt

Reputation: 377

This is what i used and it simply takes care of days or Min's for you as well as giving you the difference time_ago_in_words simply pass a Datetime, Date or Time object and it will return the difference that is human readable. time_ago_in_words(@post.created_at)

Upvotes: -1

Related Questions