Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 473
John Avatar asked Jun 20 '15 10:06

John


People also ask

How do you find the difference between two timestamps in minutes?

Discussion: If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

How do you tell the time difference in Ruby?

Because when hours_elapsed '2015-12-31 22:00:00 +0100', '2015-12-31 02:00:00 +0100' would give 4 hours_elapsed '2015-12-21 22:00:00 +0100', '2015-12-31 02:00:00 +0100' would give 220.0 and I'm only need the hours and min.

How do you find the difference between two dates in hours?

Dates and times in Excel are stored as a date number, which is the number of days since 1 January 1900, with the value after the decimal point representing the time of day. To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.


2 Answers

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
like image 56
Doug Avatar answered Sep 20 '22 12:09

Doug


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
like image 34
Pavan Avatar answered Sep 18 '22 12:09

Pavan