Calculate difference in months between two dates with Groovy

心不动则不痛 提交于 2019-12-02 03:24:08

问题


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?


回答1:


monthBetween = (start[Calendar.MONTH] - end[Calendar.MONTH]) + 1
yearsBetween = start[Calendar.YEAR] - end[Calendar.YEAR]
months = monthBetween + (yearsBetween * 12)



回答2:


(start[Calendar.MONTH]-end[Calendar.MONTH]+1)+((start[Calendar.YEAR]-end[Calendar.YEAR])*12)



回答3:


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() 



回答4:


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.




回答5:


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




回答6:


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

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