Subtract n hours from a DateTime in Ruby

后端 未结 11 1352
别那么骄傲
别那么骄傲 2020-12-14 06:02

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

11条回答
  •  难免孤独
    2020-12-14 07:05

    If you are working in Rails, the following super-intutive possibility exists:

    > Time.now - 12.hours
    => 2019-08-19 05:50:43 +0200
    

    (This also works with seconds, minutes, days, and years)

    if you're using just Ruby, DateTime can't do this, but Time can:

    t = Time.now
    t = t - (hours*60**2)
    

    Note that Time also stores date information, it's all a little strange.

    If you have to work with DateTime

    DateTime.commercial(date.year,date.month,date.day,date.hour-x,date.minute,date.second)
    

    might work, but is ugly. The doc says DateTime is immutable, so I'm not even sure about - and <<

提交回复
热议问题