Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting dates in ruby

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?

like image 959
alex9311 Avatar asked Jul 19 '26 18:07

alex9311


2 Answers

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
like image 87
the Tin Man Avatar answered Jul 22 '26 09:07

the Tin Man


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.

like image 39
Labib Ismaiel Avatar answered Jul 22 '26 07:07

Labib Ismaiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!