红宝石日期时间有add_days吗?

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

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

Jirapong asked 2020-07-30T23:07:17Z
5个解决方案
76 votes

Date类提供了执行此操作的+运算符。

>> d = Date.today
=> #<Date: 4910149/2,0,2299161>
>> d.to_s
=> "2009-08-31"
>> (d+3).to_s
=> "2009-09-03"
>> 
Steve Weet answered 2020-07-30T23:07:32Z
24 votes

在Rails中,有Fixnum类非常有用的方法(此处TimeFixnum。例如: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

这些对于Time类也很方便。

PS:需要Active Support Core扩展才能在Ruby中使用它们

require 'active_support/core_ext'
Jiemurat answered 2020-07-30T23:08:00Z
14 votes

从Date类:

+(n)

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

n可能为负值,在这种情况下,新日期早于当前日期; 但是,#-()可能更直观。

如果n不是数字,则将引发TypeError。 特别是,两个日期不能互相添加。

ire_and_curses answered 2020-07-30T23:08:38Z
9 votes

我认为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)>

[HTTP://Ruby-doc.org/身体的利弊-2.3.1/lib doc/达特/R doc/date.HTML#method-i-next_大约.]

NilColor answered 2020-07-30T23:09:02Z
1 votes
Date.new(2001,9,01).next_day(30) # 30 - numbers of day 
# => #<Date: 2001-10-01 ...
Evan Ross answered 2020-07-30T23:09:17Z
translate from https://stackoverflow.com:/questions/1356457/is-there-an-add-days-in-ruby-datetime