Maxence
Maxence

Reputation: 2339

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

Upvotes: 0

Views: 44

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

You need to first convert the local time (time1) to UTC time, or UTC time (time2) to local time.

require 'time'

time1 = Time.parse('2016-09-21 19:44:52 +0200')
  #=> 2016-09-21 19:44:52 +0200 
time2 = Time.parse('2016-09-21 17:23:16 UTC')
  #=> 2016-09-21 17:23:16 UTC 

(time1.utc - time2)/60
  #=> 21.6

Upvotes: 1

user6225298
user6225298

Reputation:

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!

Upvotes: 2

Related Questions