Java Date month difference

2019-01-04 14:20发布

I have start date and end date.

I need the number of months between this two dates in Java.

For example

  • From date: 2009-01-29
  • To date: 2009-02-02

It has one jan date and one Feb date.

It should return 2.

标签: java date
21条回答
萌系小妹纸
2楼-- · 2019-01-04 14:34

Java 8 solution:

@Test
public void monthBetween() {

    LocalDate d1 = LocalDate.of(2013, Month.APRIL, 1);
    LocalDate d2 = LocalDate.of(2014, Month.APRIL, 1);

    long monthBetween = ChronoUnit.MONTHS.between(d1, d2);

    assertEquals(12, monthBetween);

}
查看更多
神经病院院长
3楼-- · 2019-01-04 14:34

A full code snippet for finding the difference of months between two date is as follows:

public String getContractMonth(String contractStart, String contractEnd) {
    SimpleDateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd");
    String months = "0";
    try {
        Date startDate = dfDate.parse(contractStart);
        Date endDate = dfDate.parse(contractEnd);

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);

        int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
        int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        months = diffMonth + "";
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (java.text.ParseException e) {
        e.printStackTrace();
    }
    return months;
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-04 14:36

Apart from using Joda time which seems to be the the favorite suggestion I'd offer the following snippet:

public static final int getMonthsDifference(Date date1, Date date2) {
    int m1 = date1.getYear() * 12 + date1.getMonth();
    int m2 = date2.getYear() * 12 + date2.getMonth();
    return m2 - m1 + 1;
}

EDIT: Since Java 8, there is a more standard way of calculating same difference. See my alternative answer using JSR-310 api instead.

查看更多
该账号已被封号
5楼-- · 2019-01-04 14:37

I had to write this implementation, becoz I had custom defined periods, which i had to look for within two dates. Here you can define you custom period and put the logic, for calculation.

Here TimePeriod is a POJO which has start, end, period start, period End

public class Monthly extends Period {

public int getPeriodCount(String startDate, String endDate, int scalar) {
    int cnt = getPeriods(startDate, endDate, scalar).size();        
    return cnt;
}

public List getPeriods(String startDate, String endDate, int scalar) {

    ArrayList list = new ArrayList();

    Calendar startCal = CalendarUtil.getCalendar(startDate);
    Calendar endCal =  CalendarUtil.getCalendar(endDate);

    while (startCal.compareTo(endCal) <= 0) {
        TimePeriod period = new TimePeriod();
        period.setStartDate(startCal.getTime());
        period.setPeriodStartDate(getPeriodStartDate((Calendar) startCal.clone()).getTime());
        Calendar periodEndCal = getPeriodEndDate((Calendar) startCal.clone(), scalar);
        period.setEndDate(endCal.before(periodEndCal) ? endCal.getTime()    : periodEndCal.getTime());
        period.setPeriodEndDate(periodEndCal.getTime());

        periodEndCal.add(Calendar.DATE, 1);
        startCal = periodEndCal;
        list.add(period);
    }

    return list;
}


private Calendar getPeriodStartDate(Calendar cal) {     
    cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE));        
    return cal;
}

private Calendar getPeriodEndDate(Calendar cal, int scalar) {

    while (scalar-- > 0) {
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        if (scalar > 0)
            cal.add(Calendar.DATE, 1);          
    }

    return cal;
}

}

查看更多
老娘就宠你
6楼-- · 2019-01-04 14:37
long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-01-29").minusMonths(1),
            LocalDate.parse("2016-02-02").plusMonths(1));
  1. 2016-01-29 to 2016-01-02 = months 1
  2. 2016-02-29 to 2016-02-02 = months 1
  3. 2016-03-29 to 2016-05-02 = months 5
查看更多
干净又极端
7楼-- · 2019-01-04 14:39

I would strongly recommend Joda-Time for this.

  1. It makes this sort of work very easy (check out Periods)
  2. It doesn't suffer from the threading issues plaguing the current date/time objects (I'm thinking of formatters, particularly)
  3. It's the basis of the new Java date/time APIs to come with Java 7 (so you're learning something that will become standard)

Note also Nick Holt's comments below re. daylight savings changes.

查看更多
登录 后发表回答