ruby datetime中是否有add_days?

Jir*_*ong 44 ruby

在C#中,DateTime类中有一个方法AddDays([天数]).

红宝石中有这样的方法吗?

Ste*_*eet 77

Date类提供了一个+操作员做到了这一点.

>> d = Date.today
=> #<Date: 4910149/2,0,2299161>
>> d.to_s
=> "2009-08-31"
>> (d+3).to_s
=> "2009-09-03"
>> 
Run Code Online (Sandbox Code Playgroud)


Jie*_*rat 24

在Rails中有非常有用的Fixnum类方法(这里nFixnum.例如:) 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
Run Code Online (Sandbox Code Playgroud)

这些也很方便Time.

PS:要求Active Support Core Extensions在Ruby中使用它们

require 'active_support/core_ext'
Run Code Online (Sandbox Code Playgroud)

  • 这些方法是特定于Rails的 (6认同)
  • 你可以在不包括整个 Rails 框架的情况下使用主动支持:`gem 'activesupport'` `require 'active_support'` `require 'active_support/core_ext'` (2认同)

ire*_*ses 14

Date类:

+(n)的

返回比当前日期晚n天的新Date对象.

n可以是负值,在这种情况下,新Date早于当前值; 但是,# - ()可能更直观.

如果n不是Numeric,则抛出TypeError.特别是,两个日期不能相互添加.


Nil*_*lor 9

我认为next_day+版本更具可读性.

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)>
Run Code Online (Sandbox Code Playgroud)

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


Eva*_*oss 5

Date.new(2001,9,01).next_day(30) # 30 - numbers of day 
# => #<Date: 2001-10-01 ...
Run Code Online (Sandbox Code Playgroud)