Is there an add_days in ruby datetime?

后端 未结 6 1265
生来不讨喜
生来不讨喜 2020-12-25 10:59

In C#, There is a method AddDays([number of days]) in DateTime class.

Is there any kind of method like this in ruby?

相关标签:
6条回答
  • 2020-12-25 11:24

    The Date class provides a + operator that does just that.

    >> d = Date.today
    => #<Date: 4910149/2,0,2299161>
    >> d.to_s
    => "2009-08-31"
    >> (d+3).to_s
    => "2009-09-03"
    >> 
    
    0 讨论(0)
  • 2020-12-25 11:36

    From the Date class:

    +(n)

    Return a new Date object that is n days later than the current one.

    n may be a negative value, in which case the new Date is earlier than the current one; however, #-() might be more intuitive.

    If n is not a Numeric, a TypeError will be thrown. In particular, two Dates cannot be added to each other.

    0 讨论(0)
  • 2020-12-25 11:39
    Date.new(2001,9,01).next_day(30) # 30 - numbers of day 
    # => #<Date: 2001-10-01 ...
    
    0 讨论(0)
  • 2020-12-25 11:41

    In Rails there are very useful methods of Fixnum class for this (here n is Fixnum. For example: 1,2,3.... ):

    Date.today + n.seconds # you can use 1.second
    Date.today + n.minutes # you can use 1.minute
    Date.today + n.hours # you can use 1.hour
    Date.today + n.days # you can use 1.day
    Date.today + n.weeks # you can use 1.week
    Date.today + n.months # you can use 1.month
    Date.today + n.years # you can use 1.year
    

    These are convenient for Time class too.

    PS: require Active Support Core Extensions to use these in Ruby

    require 'active_support/core_ext'
    
    0 讨论(0)
  • 2020-12-25 11:49

    You can also use the advance (https://apidock.com/rails/DateTime/advance) method. I think it's more legible.

    date = Date.today
    # => Fri, 25 Oct 2019
    date.advance(days: 10)
    # => Mon, 04 Nov 2019
    
    time = DateTime.now
    # => Fri, 25 Oct 2019 14:32:53 +0200
    time.advance(months:1, weeks: 2, days: 2, hours: 6, minutes: 6, seconds: 34)
    # => Wed, 11 Dec 2019 20:39:27 +0200
    
    0 讨论(0)
  • 2020-12-25 11:50

    I think next_day is more readable than + version.

    require 'date'
    
    DateTime.new(2016,5,17)
    # => #<DateTime: 2016-05-17T00:00:00+00:00 ((2457526j,0s,0n),+0s,2299161j)>
    DateTime.new(2016,5,17).next_day(10)
    # => #<DateTime: 2016-05-27T00:00:00+00:00 ((2457536j,0s,0n),+0s,2299161j)>
    Date.new(2016,5,17)
    # => #<Date: 2016-05-17 ((2457526j,0s,0n),+0s,2299161j)>
    Date.new(2016,5,17).next_day(10)
    # => #<Date: 2016-05-27 ((2457536j,0s,0n),+0s,2299161j)>
    

    http://ruby-doc.org/stdlib-2.3.1/libdoc/date/rdoc/Date.html#method-i-next_day.

    0 讨论(0)
提交回复
热议问题