I have a class that has two params: start_date
and end_date
.
Those are formatted like - 2012-07-12 and 2012-07-24.
I was to subtract end_date
from start_date
.
Previous Googling has left me high and dry. Should I convert these to something else to do subtraction?
Convert them into dates and subtract them:
require 'date'
start_date = Date.parse('2012-07-12')
end_date = Date.parse('2012-07-24')
(start_date - end_date).to_i
=> -12
If you want the number of days (end_date-start_date).days
should work fine. You'll probably get a Rational
number of days, in which case you can just use to_i
If i am not miskaten, the params come in form of a String
, so you have to convert it to a Date
, DateTime
, or Time
to do math operations with them.
You can refer to this question to more details.
How can I find the number of days between two Date objects in Ruby?
You can just substract two DateTime objects
Using 1.9
require 'date'
DateTime.parse(end_date) - DateTime.parse(start_date)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.