如何将可变月数添加到 Ruby 中的日期(避免使用循环)
How do I add variable number of months to a date in Ruby (avoid using loop)
是否有类似于下面 Ruby 中的代码,其中 X 代表要添加到今天日期的月数,但来自变量
Time.zone.today + X.month ## X comes from a variable
最好不要使用循环,因为 'm' 在下面的示例中可以是大数
def add_months_to_today(m)
number_of_months_to_add = m.to_i
return_date = Time.zone.today
if m.to_i > 0
(1..number_of_months_to_add).each do |i|
return_date = return_date + 1.month
end
end
return_date
end
您的代码运行良好:
x = 4
Time.zone.today + x.month
#=> Sun, 29 Sep 2019
month
是在 Integer
上定义的方法。整数是作为文字还是作为变量给出并不重要。接收者必须是 Integer
.
您也可以调用 Date.current
:
而不是 Time.zone.today
Date.current + 4.month #=> Sun, 29 Sep 2019
Rails还在Date
: (also via DateAndTime::Calculations
)
的基础上增加了多种其他方法
Date.current.advance(months: 4) #=> Sun, 29 Sep 2019
Date.current.months_since(4) #=> Sun, 29 Sep 2019
4.months.since(Date.current) #=> Sun, 29 Sep 2019
以上也适用于 Time
:
的实例
Time.current.advance(months: 4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
Time.current.months_since(4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
4.months.since #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
当只处理日期时,也可以使用Ruby的built-in >>
or next_month
:
Date.current >> 4
#=> Sun, 29 Sep 2019
Date.current.next_month(4)
#=> Sun, 29 Sep 2019
请注意,您可以在上述所有示例中互换使用 4
和 x
。
是否有类似于下面 Ruby 中的代码,其中 X 代表要添加到今天日期的月数,但来自变量
Time.zone.today + X.month ## X comes from a variable
最好不要使用循环,因为 'm' 在下面的示例中可以是大数
def add_months_to_today(m)
number_of_months_to_add = m.to_i
return_date = Time.zone.today
if m.to_i > 0
(1..number_of_months_to_add).each do |i|
return_date = return_date + 1.month
end
end
return_date
end
您的代码运行良好:
x = 4
Time.zone.today + x.month
#=> Sun, 29 Sep 2019
month
是在 Integer
上定义的方法。整数是作为文字还是作为变量给出并不重要。接收者必须是 Integer
.
您也可以调用 Date.current
:
Time.zone.today
Date.current + 4.month #=> Sun, 29 Sep 2019
Rails还在Date
: (also via DateAndTime::Calculations
)
Date.current.advance(months: 4) #=> Sun, 29 Sep 2019
Date.current.months_since(4) #=> Sun, 29 Sep 2019
4.months.since(Date.current) #=> Sun, 29 Sep 2019
以上也适用于 Time
:
Time.current.advance(months: 4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
Time.current.months_since(4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
4.months.since #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
当只处理日期时,也可以使用Ruby的built-in >>
or next_month
:
Date.current >> 4
#=> Sun, 29 Sep 2019
Date.current.next_month(4)
#=> Sun, 29 Sep 2019
请注意,您可以在上述所有示例中互换使用 4
和 x
。