Time manipulation in ruby

后端 未结 5 841
北荒
北荒 2021-02-05 02:49

I want to create a DateTime instance that lies 20 minutes and 10 seconds in the future. I tried around with Time and DateTime in irb, but can\'t seem to figure out a way that re

5条回答
  •  忘掉有多难
    2021-02-05 03:37

    Pure Ruby (no Rails)

    class Numeric
      def minutes; self/1440.0 end
      alias :minute :minutes
    
      def seconds; self/86400.0 end
      alias :second :seconds
    end
    

    Where 1440 is the number of minutes and 86400 is the number of seconds in a day. Based on how Rails does.

    Then you can just let the magic happen:

    d + 20.minutes + 10.seconds
    

    Source: https://github.com/rails/rails/blob/v6.0.3.1/activesupport/lib/active_support/core_ext/numeric/time.rb

提交回复
热议问题