Time manipulation in ruby

后端 未结 5 798
北荒
北荒 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:38

    A Time is a number of seconds since an epoch whereas a DateTime is a number of days since an epoch which is why adding 1 to a DateTime adds a whole day. You can however add fractions of a day, for example

    d = DateTime.now
    d + Rational(10, 86400)
    

    Will add 10 seconds to d (since there are 86400 seconds in a day).

    If you are using Rails, Active Support adds some helper methods and you can do

    d + 20.minutes + 10.seconds
    

    Which will do the right thing is d is a DateTime or a Time. You can use Active Support on its own, and these days you can pull in just the bits you need. I seem to recall that this stuff is in activesupport/duration. I believe there are a few other gems that offer help with time handling too.

提交回复
热议问题