Muflix
Muflix

Reputation: 6778

Rails date difference between now and created_at in days

Hello i have table with ticket where i have valid_from column in DATETIME format and validity column in INTEGER. Now i need find out how many days is ticket active (for how many days it will inactive). Im using integer converting to getting days but it looks that return not days.

>> valid_from #DATETIME
=> Thu, 12 Sep 2013 18:24:52 UTC +00:00
>> validity #INTEGER
=> 14
>> DateTime.now
=> Sat, 14 Sep 2013 13:17:32 -0500
>> ((valid_from + validity.days) - DateTime.now.utc).to_i
=> 1037228

command ((valid_from + validity.days) - DateTime.now.utc).to_i returned 1037228 days.. where is a mistake ? thank you

edit:

((valid_from + validity.days) - DateTime.now.utc).days

returns 1036588.3133747578 days

Upvotes: 2

Views: 3936

Answers (2)

Tyler
Tyler

Reputation: 11509

This works just fine on my machine, gives

valid_from = DateTime.now.utc - 2.days
=> Thu, 12 Sep 2013 18:34:45 +0000 
valid_from
=> Thu, 12 Sep 2013 18:34:45 +0000 
validity
=> 14 
DateTime.now
=> Sat, 14 Sep 2013 11:35:11 -0700 
((valid_from + validity.days) - DateTime.now.utc).to_i
=> 11

I don't think there is an error in your formula, etc. There may be some issue with the time settings on your machine; check to make sure you're using the same time zone everywhere.

EDIT

Just realized your valid_from is in a different format. Try replacing it with valid_from.to_datetime in your formula.

Upvotes: 2

oivoodoo
oivoodoo

Reputation: 794

Lets try to write something like this:

((valid_from + validity.days) - Date.today).to_i

Upvotes: 0

Related Questions