This seems like a real straightforward thing to do but I'm having trouble with it. I have a date and I want to find out how many days are between today and that date. Here is my attempt in ruby console:
>> Date.today
=> Wed, 31 Jul 2013
>> date_time
=> Fri Jul 26 00:40:12 -0700 2013
>> Date.parse(date_time.to_s)
=> Wed, 26 Jul 0013
>> Date.today-Date.parse(date_time.to_s)
=> Rational(730492, 1)
Why am I getting this back instead of just an integer?
It looks like date_time is already a DateTime object, so why convert it to a string and reparse it?
require 'date'
date_time = DateTime.parse('Fri Jul 26 00:40:12 -0700 2013')
date_time.class # => DateTime
(Date.today - date_time).to_i # => 4
If you want to ignore the time component of the DateTime, convert it to a date:
require 'date'
date_time = DateTime.parse('Fri Jul 26 00:40:12 -0700 2013')
date_time.class # => DateTime
(Date.today - date_time.to_date).to_i # => 5
Try:
result = Date.new(0) + ("2013-07-31".to_date - "2013-06-31".to_date)
and then you can use result.year, result.month, etc.
Or, you can use to_i like (Date.parse('2013-07-31')-Date.parse('2013-06-31')).to_i
because it seems you are subtracting strings rather than integers, and to_i solves it.
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