使用Groovy计算两个日期之间的月份差异 [英] Calculate difference in months between two dates with Groovy

查看:1550
本文介绍了使用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)

这篇关于使用Groovy计算两个日期之间的月份差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆