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()
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)
(start[Calendar.MONTH]-end[Calendar.MONTH]+1)+((start[Calendar.YEAR]-end[Calendar.YEAR])*12)
Just for fun (as it probably less readable, and uses more resources), you could also do:
months = (start..end).collect { [ it[ Calendar.YEAR ], it[ Calendar.MONTH ] ] }
.unique()
.size()
I agree with @JonSkeet: you should continue to use Joda-Time. IMO, Joda-Time and Groovy are a great fit for each other.
The closest that you can come (that I could find) would be to use the additional Date methods in the Groovy JDK to do this:
int differenceInDays = start - end
which calculates the difference between the two dates in days. This leaves you to convert the days into months yourself, which sucks.
Stick with Joda-Time.
If you want to get difference in months by month name, instead of days and weeks, you can do this.
Ex: December 7, 2013 vs January 21, 2014 will give you a difference of 1
Date dateFrom = Date.parse("yyyy-MM-dd", "2013-12-07")
Date dateTo = Date.parse("yyyy-MM-dd", "2014-01-21")
def diffMonths = { Date start, Date end ->
int diffYears = (start[Calendar.YEAR] - end[Calendar.YEAR]) * 12
int diffMonths = start[Calendar.MONTH] - end[Calendar.MONTH]
return diffYears + diffMonths
}
println diffMonths(dateTo, dateFrom)
The following will output 1
As Jon Skeet mentioned, you are better of using Joda-Time then wrapping your head around this topic.
Be aware though that Joda-Time returns the number of full months between the two dates, including a proper handling of daylight-savings time.
来源:https://stackoverflow.com/questions/10820022/calculate-difference-in-months-between-two-dates-with-groovy