Maxence Maxence - 2 months ago 22
Ruby Question

Date substraction returning odd value

I am trying to allow the destruction of a record only if this record has been created within the last 30 minutes.

Then I retrieve the

created_at
value of my record (date2) and check against
Time.now
(date1) :

date1 = 2016-09-21 19:44:52 +0200
date2 = 2016-09-21 17:23:16 UTC


then I just substract the two :

(date1-date2).minutes.to_i


But the result returned is in the 10s of thousands (something like 97000) and increasing very fast when i refresh..(as
Time.now
changes) whereas we should only get 141 minutes as per above example values

Answer

The .minutes is what makes the thing don't work. Remove it and it should work. If you want to find the gap in minutes between to date you just have to substract them, divide the result per 60 and round it.

((date1 - date2) / 60).round

Hope it helped, happy ruby coding!