Java Date month difference

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.


    As the rest say, if there's a library that will give you time differences in months, and you can use it, then you might as well.

    Otherwise, if y1 and m1 are the year and month of the first date, and y2 and m2 are the year and month of the second, then the value you want is:

    (y2 - y1) * 12 + (m2 - m1) + 1;
    

    Note that the middle term, (m2 - m1), might be negative even though the second date is after the first one, but that's fine.

    It doesn't matter whether months are taken with January=0 or January=1, and it doesn't matter whether years are AD, years since 1900, or whatever, as long as both dates are using the same basis. So for example don't mix AD and BC dates, since there wasn't a year 0 and hence BC is offset by 1 from AD.

    You'd get y1 etc. either from the dates directly if they're supplied to you in a suitable form, or using a Calendar.


    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.


    I would strongly recommend Joda-Time for this.

  • It makes this sort of work very easy (check out Periods)
  • It doesn't suffer from the threading issues plaguing the current date/time objects (I'm thinking of formatters, particularly)
  • 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.

    链接地址: http://www.djcxy.com/p/60614.html

    上一篇: lang添加清单文件

    下一篇: Java日期月份差异