像这样的东西?
require 'date'
def months_between_dates(date_1, date_2)
diff_in_years = (date_1.year-date_2.year)*12
diff_in_months = date_1.month-date_2.month
return (diff_in_years + diff_in_months).abs
end
start_date = Date.new(2011,12,31)
test_date = Date.new(2013,01,01)
test_date_2 = Date.new(2014,02,01)
p months_between_dates(start_date, test_date) # => 13
p months_between_dates(start_date, test_date_2) # => 26
编辑:
如果您知道您将始终与特定日期进行比较,那么这里的奖励是具有默认值的版本。逻辑是一样的,只是简短而不是可读:
# Call by passing one or two dates:
def delta_months(x, y=Date.new(2011,12,31))
((x.year-y.year)*12+(x.month-y.month)).abs
end
p delta_months(test_date) # => 13
编辑2:
正如 dax 指出的那样,我的函数不提供任何形式的验证,以下是您将如何实现它:
MIN_DATE, MAX_DATE = Date.new(2011,12,31), Date.new(2032,1,1)
date_range = MIN_DATE..MAX_DATE
test_date = Date.new(2064,1,1)
raise "Date out of range, must be between #{MIN_DATE} and #{MAX_DATE}." unless date_range.cover? test_date # => Date out of range, must be between 2011-12-31 and 2032-01-01. (RuntimeError)
delta_months(test_date) # Never called unless good date is provided.