首页 > 解决方案 > 如何在 Ruby 中将可变月份数添加到日期(避免使用循环)

问题描述

是否有类似于 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

标签: rubyruby-on-rails-4

解决方案


您的代码运行良好:

x = 4
Time.zone.today + x.month
#=> Sun, 29 Sep 2019

month是在 上定义的方法Integer。整数是作为文字还是作为变量给出并不重要。接收器必须是一个Integer.


而不是Time.zone.today你也可以打电话Date.current

Date.current + 4.month  #=> Sun, 29 Sep 2019

Rails 还添加了多种其他方法Date:(也通过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 内置的>>or :next_month

Date.current >> 4
#=> Sun, 29 Sep 2019

Date.current.next_month(4)
#=> Sun, 29 Sep 2019

请注意,您可以在上述所有示例中使用4x互换。


推荐阅读