我正在尝试从Date中减去月份,但结果不准确
end_date = Date.parse("30-09-2019")
end_date - 1.months
返回2019年8月30日
example 30-09-2019 - 1.month to give 31 - 08 - 2019
example 15-09-2019 - 1.month to give 14 - 08 - 2019
我正在尝试从Date中减去月份,但结果不准确
end_date = Date.parse("30-09-2019")
end_date - 1.months
example 30-09-2019 - 1.month to give 31 - 08 - 2019
example 15-09-2019 - 1.month to give 14 - 08 - 2019
Date.new(2019,9,30) - 1.month
产生Fri,30 Aug 2019
的原因仅仅是因为1.month
不是30天,而是2629746秒(30.436875天)的静态值。
date = Date.new(2019,30)
1.month == 30.436875.days #=> true
date - 30.days #=> Sat,31 Aug 2019
date - 30.436875.days #=> Fri,30 Aug 2019
您可以找到记录在here中的这些静态值。
,您可以使用几种方法从Ruby中的日期中减去月份,以下指南非常全面地介绍了您可以在Ruby中执行的所有日期操作方法:
Ruby Cookbook,2nd Edition by Leonard Richardson,Lucas Carlson
1。使用
require 'date'
end_date = Date.parse("30-09-2019")
end_date = end_date << 1
print(end_date.strftime("%d-%m-%Y"))
2。使用prev_month()
require 'date'
end_date = Date.parse("30-09-2019")
end_date = end_date.prev_month //this would give the desired result
print(end_date.strftime("%d-%m-%Y"))
,
您可以使用ActiveSupport中的DateTime#advance
。
使用日期来提供精确的时间计算,包括年,月和月 天。 options参数使用以下任何一个键获取哈希值: :年,:月,:周,:天,:小时,:分钟,:秒。
irb(main):001:0> end_date = Date.parse("30-09-2019")
=> Mon,30 Sep 2019
irb(main):002:0> end_date.advance(months: 1)
=> Wed,30 Oct 2019
irb(main):003:0> end_date.advance(months: -1)
=> Fri,30 Aug 2019
irb(main):004:0> end_date.advance(months: -1,days: 2)
=> Sun,01 Sep 2019
是的,使用.advance
进行倒退在语义上是很奇怪的,但是在使用负值时效果很好。不幸的是,没有逆方法。