Subtract n hours from a DateTime in Ruby

后端 未结 11 1354
别那么骄傲
别那么骄傲 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:01

    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 and Fixnum to do what you want:

    require 'date'
    
    # A placeholder class for holding a set number of hours.
    # Used so we can know when to change the behavior
    # of DateTime#-() by recognizing when hours are explicitly passed in.
    
    class Hours
       attr_reader :value
    
       def initialize(value)
          @value = value
       end
    end
    
    # Patch the #-() method to handle subtracting hours
    # in addition to what it normally does
    
    class DateTime
    
       alias old_subtract -
    
       def -(x) 
          case x
            when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec)
            else;       return self.old_subtract(x)
          end
       end
    
    end
    
    # Add an #hours attribute to Fixnum that returns an Hours object. 
    # This is for syntactic sugar, allowing you to write "someDate - 4.hours" for example
    
    class Fixnum
       def hours
          Hours.new(self)
       end
    end
    

    Then you can write your code like this:

    some_date = some_date - n.hours
    

    where n is the number of hours you want to substract from some_date

提交回复
热议问题