Calculate difference in months between two dates with Groovy

萝らか妹 提交于 2019-12-02 00:38:10
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!