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?
You didn't say what use you need to make of the value you get, but what about just dividing your hours by 24 so you're subtracting a fraction of a day?
If I'm allowed to use
Time
instead ofDateTime
(There are several ways to translate one to another):I like using the helpers in active_support. It makes it really clean and easy to read.
See the example below:
There might be a way to use that kind of syntax to do what you are looking for, if the current date is used.
You could do this.
You can use this :
For example
Time.now.ago(7200)
will give the date and time that was before 2 hours from now.EDIT: Take a look at this question before you decide to use the approach I've outlined here. It seems it may not be best practice to modify the behavior of a base class in Ruby (which I can understand). So, take this answer with a grain of salt...
MattW's answer was the first thing I thought of, but I also didn't like it very much.
I suppose you could make it less ugly by patching
DateTime
andFixnum
to do what you want:Then you can write your code like this:
where
n
is the number of hours you want to substract fromsome_date