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
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With