Rails以月为单位计算日期范围 [英] Rails calculate date range in months
问题描述
如何计算两个日期的差异?此外,它会有所作为,我正在使用Date对象,而不是DateTime。另外,一些四舍五入的选项可能很好,所以我可以控制我是否要在部分月份进行整理。
How do I calculate the difference of two dates in months? Also, incase it makes a difference, I am working with Date objects, not DateTime. Also, some rounding options might be nice so I can control if I want to round up or down on partial months.
谢谢!
推荐答案
从另一个减去一个Date或DateTime将会产生一个小数的天数,但是这可以被计算为 Float
或 Fixnum
根据需要。
Subtracting one Date or DateTime from another will yield the number of days as a fraction, but this can be evaluated as a Float
or Fixnum
as required.
例如:
(Date.today - Date.today.advance(:months => -3)).to_f
# => 89.0
今天和三个月前相同的日历日期之间有89.0天。如果您使用30天的月份,或者平均30.4375的工作时间,则从现在到现在结束2.92个月,或舍入到最接近的整数,3。
There were 89.0 days between today and the same calendar date three months ago. If you work this using 30-day months, or 30.4375 as they are on average, you end up with 2.92 months elapsed between then and now, or rounded up to the nearest integer, 3.
如果您要计算日历月份的确切数量,那就更棘手,但可以完成。
If you want to compute the precise number of calendar months, that is trickier, but can be done.
这篇关于Rails以月为单位计算日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!