查找Ruby on Rails中两个date之间的月数

我有两个Ruby on Railsdate时间对象。 如何find它们之间的月数? (记住他们可能属于不同的年份)

(date2.year * 12 + date2.month) - (date1.year * 12 + date1.month) 

更多信息在http://www.ruby-forum.com/topic/72120

更准确的答案会考虑远处的日子。

例如,如果您认为2000年4月28/4/20001/5/2000 1月5日的月份距离是0而不是1 ,那么您可以使用:

 (date2.year - date1.year) * 12 + date2.month - date1.month - (date2.day >= date1.day ? 0 : 1) 

试试看

 ((date2.to_time - date1.to_time)/1.month.second).to_i 

您可以将这个问题改为“在几个月的开始之间有多less个第一天”,然后使用函数式的数据转换:

 (date1.beginning_of_month...date2.beginning_of_month).select { |date| date.day == 1 }.size 

我发现的另一个解决scheme(build立在这里已经发布的解决scheme)是为了如果你想要的结果包括一个月的小数。 例如,距离是1.2 months

 ((date2.to_time - date1.to_time)/1.month.second).round(1) #Tenth of a month Ex: 1.2 ((date2.to_time - date1.to_time)/1.month.second).round(2) #Hundreth, ex: 1.23 months etc... 
 start_date = Date.today end_date = Date.today+90 months = (end_date.month+end_date.year*12) - (start_date.month+start_date.year*12) //months = 3 
 def difference_in_months(date1, date2) month_count = (date2.year == date1.year) ? (date2.month - date1.month) : (12 - date1.month + date2.month) month_count = (date2.year == date1.year) ? (month_count + 1) : (((date2.year - date1.year - 1 ) * 12) + (month_count + 1)) month_count end 

我需要在两个date之间确切的月数(包括小数),并为它写下面的方法。

 def months_difference(period_start, period_end) period_end = period_end + 1.day months = (period_end.year - period_start.year) * 12 + period_end.month - period_start.month - (period_end.day >= period_start.day ? 0 : 1) remains = period_end - (period_start + months.month) (months + remains/period_end.end_of_month.day).to_f.round(2) end 

如果比较说9月26日到9月26日(同一天),我计算为1天。 如果你不需要,你可以删除方法中的第一行: period_end = period_end + 1.day

它通过以下规格:

 expect(months_difference(Date.new(2017, 8, 1), Date.new(2017, 8, 31))).to eq 1.0 expect(months_difference(Date.new(2017, 8, 1), Date.new(2017, 8, 30))).to eq 0.97 expect(months_difference(Date.new(2017, 8, 1), Date.new(2017, 10, 31))).to eq 3.0 # Overlapping february (28 days) still counts Feb as a full month expect(months_difference(Date.new(2017, 1, 1), Date.new(2017, 3, 31))).to eq 3.0 expect(months_difference(Date.new(2017, 2, 10), Date.new(2017, 3, 9))).to eq 1.0 # Leap year expect(months_difference(Date.new(2016, 2, 1), Date.new(2016, 2, 29))).to eq 1.0