Subtract n hours from a DateTime in Ruby

Tillmann Carlos Bielefeld picture Tillmann Carlos Bielefeld · Oct 26, 2008 · Viewed 87.9k times · Source

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?

Answer

Daniel Beardsley picture Daniel Beardsley · Oct 27, 2008

You could do this.

adjusted_datetime = (datetime_from_form.to_time - n.hours).to_datetime