ruby - 如何在 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
解决方案
您的代码运行良好:
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
请注意,您可以在上述所有示例中使用4
和x
互换。
推荐阅读
- node.js - 如何让一切按顺序发生(Node js)
- javascript - Firefox 扩展 Javascript YouTube HTML 视频未定义
- javascript - 我的不和谐机器人忽略了其中包含大写字母的命令
- ocaml - 如何运行 Ocaml 模拟
- java - 使用powershell安装java不起作用
- api - Deribit 代码对我不起作用.. 有人有什么建议吗?
- javascript - 为什么我的函数在 API 中停止工作?
- css - 如何使锚点与iOS(WebKit)上的文本在同一行开始?
- amazon-web-services - 如何让python包`awswranger`接受自定义`endpoint_url`
- javascript - NodeJS - 使用 JSON.parse(JSON.stringify()) 后如何从缓冲区中检索原始数据