You could do this.
adjusted_datetime = (datetime_from_form.to_time - n.hours).to_datetime
You can just subtract less than one whole day:
two_hours_ago = DateTime.now - (2/24.0)
This works for minutes and anything else too:
hours = 10
minutes = 5
seconds = 64
hours = DateTime.now - (hours/24.0) #<DateTime: 2015-03-11T07:27:17+02:00 ((2457093j,19637s,608393383n),+7200s,2299161j)>
minutes = DateTime.now - (minutes/1440.0) #<DateTime: 2015-03-11T17:22:17+02:00 ((2457093j,55337s,614303598n),+7200s,2299161j)>
seconds = DateTime.now - (seconds/86400.0) #<DateTime: 2015-03-11T17:26:14+02:00 ((2457093j,55574s,785701811n),+7200s,2299161j)>
If floating point arithmetic inaccuracies are a problem, you can use Rational
or some other safe arithmetic utility.
The advance method is nice if you want to be more explicit about behavior like this.
adjusted = time_from_form.advance(:hours => -n)
You just need to take off fractions of a day.
two_hours_ago = DateTime.now - (2.0/24)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With