I have a Ruby DateTime which gets filled from a form. Additionally I have n hours from the form as well. I'd like to subtract those n hours from the previous DateTime. (To get a time range).
DateTime has two methods "-" and "<<" to subtract day and month, but not hour. (API). Any suggestions how I can do that?
The advance method is nice if you want to be more explicit about behavior like this.
You just need to take off fractions of a day.
n/24.0
trick won't work properly as floats are eventually rounded:You can, however, use Rational class instead:
DateTime
can't do this, butTime
can:Note that
Time
also stores date information, it's all a little strange.If you have to work with
DateTime
might work, but is ugly. The doc says
DateTime
is immutable, so I'm not even sure about-
and<<
You can just subtract less than one whole day:
This works for minutes and anything else too:
If floating point arithmetic inaccuracies are a problem, you can use
Rational
or some other safe arithmetic utility.