Jason
Jason

Reputation: 23395

Why does this DateTime subtraction operation return invalid results?

I have two DateTime objects, one in the past and one representing the current datetime. I am trying to find out how many minutes have passed between the two:

past = "Wed, 03 Jul 2013 00:59:39 UTC +00:00".to_datetime
now  = "Wed, 03 Jul 2013 01:04:19 +0100".to_datetime

seconds = (now - past)             #result is (-83/2160)

This is incorrect. Seconds should be 280, the number of seconds that have passed between the two times.

Upvotes: 1

Views: 150

Answers (1)

oldergod
oldergod

Reputation: 15010

Subtracting two DateTimes returns the elapsed time in days.

So you can do:

past = "Wed, 03 Jul 2013 00:59:39 UTC +00:00".to_datetime
now  = "Wed, 03 Jul 2013 01:04:19 +0100".to_datetime
seconds = (now - past) * 1.day
# => -3320.0

Or you could do:

seconds = (now.to_i - past.to_i)
# => -3320

※ The result is negative because of the Timezone.

past.utc
# => Wed, 03 Jul 2013 00:59:39 +0000 
now.utc
# => Wed, 03 Jul 2013 00:04:19 +0000 

You can see that now is actually older than past.

Upvotes: 1

Related Questions