我想要 2 之间java.util.Date
的月数,而不计算月中的天数。所以我只想要比较中的年份和月份。
例子:
monthsBetween(new Date(2012,01,28), new Date(2012,02,01)) ---> 1
monthsBetween(new Date(2012,02,27), new Date(2012,02,28)) ---> 0
monthsBetween(new Date(2012,03,28), new Date(2012,07,01)) ---> 4
我已经使用 Joda-time 尝试过这个(返回 0,预期为 1):
private static int monthsBetween(final Date fromDate, final Date toDate) {
DateTime date1 = new DateTime().withDate(2012, 1, 20);
DateTime date2 = new DateTime().withDate(2012, 2, 13);
PeriodType monthDay = PeriodType.yearDayTime().withDaysRemoved();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
return months;
}
还有这个(相同的结果),使用 Joda-time:
private static int monthsBetween(final Date fromDate, final Date toDate) {
return Months.monthsBetween(new DateTime(fromDate), new DateTime(toDate).getMonths();
}
我怎样才能做到这一点?