使用Groovy计算两个日期之间的月份差异
问题描述:
我需要计算两个日期之间的差异。
I need to calculate the difference in months between two dates.
start = new Date(112, 4, 30) // Wed May 30 00:00:00 CEST 2012
end = new Date(111, 9, 11) // Tue Oct 11 00:00:00 CEST 2011
assert 8 == monthsBetween(start, end)
Using Joda-Time it's really easy to achieve this with something like this:
months = Months.monthsBetween(start, end).getMonths()
我以Groovy的方式实现了这一点,而不使用其他库?
How can I achieve this in a Groovy way, without using other libraries?
答
monthBetween = (start[Calendar.MONTH] - end[Calendar.MONTH]) + 1
yearsBetween = start[Calendar.YEAR] - end[Calendar.YEAR]
months = monthBetween + (yearsBetween * 12)