2 java.util.Date之间的月份数,不包括月的日期 [英] Number of months between 2 java.util.Date, excluding day of month

查看:182
本文介绍了2 java.util.Date之间的月份数,不包括月的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在2 java.util.Date 之间的月份数,而不计算每月的天数。
所以我只想要比较年和月。

I want the number of months between 2 java.util.Date's, without the days in month counted. So I just want the year and month in the comparison.

 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

我尝试过这个(返回0,预期为1),使用Joda-time:

I have tried this (returns 0, expected 1), using Joda-time:

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:

And also this (same results), using Joda-time:

private static int monthsBetween(final Date fromDate, final Date toDate) {
        return Months.monthsBetween(new DateTime(fromDate), new   DateTime(toDate).getMonths();
    }

我该怎么做?

推荐答案

你正在要求整个月的数量 - 这跟说忽略一个月的日子不一样部分。

You're asking for the number of whole months - which isn't the same as saying "ignore the day of month part".

首先,我建议使用 LocalDate 而不是 DateTime ,理想情况下不要使用 java.util.Date ,并将您的输入作为 LocalDate 开始(例如通过解析文本直线或者您的数据来自哪里。)将这两个日期的月份日期设置为1,然后 在几个月内取得差异:

To start with, I'd suggest using LocalDate instead of DateTime for the computations. Ideally, don't use java.util.Date at all, and take your input as LocalDate to start with (e.g. by parsing text straight to that, or wherever your data comes from.) Set the day of month to 1 in both dates, and then take the difference in months:

private static int monthsBetweenIgnoreDays(LocalDate start, LocalDate end) {
    start = start.withDayOfMonth(1);
    end = end.withDayOfMonth(1);
    return Months.monthsBetween(start, end).getMonths();
}

这篇关于2 java.util.Date之间的月份数,不包括月的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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