Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of months between 2 java.util.Date, excluding day of month

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.

Example:

 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

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;
 }

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();
    }

How can I accomplish this?

like image 986
Filip Avatar asked Nov 26 '12 14:11

Filip


People also ask

How do I calculate the difference between two Java Util dates?

Parse both start_date and end_date from a string to produce the date, this can be done by using parse() method of the simpleDateFormat class. Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime().

How do you count months in Java?

Once you have the LocalDate, you can use Months. monthsBetween() and Years. yearsBetween() method to calcualte the number of months and years between two dates in Java. LocalDate jamesBirthDay = new LocalDate(1955, 5, 19); LocalDate now = new LocalDate(2015, 7, 30); int monthsBetween = Months.

How do you check month is 30 or 31 days?

If the month is on a knuckle, it has 31 days. Otherwise is has 30 or less days.

Can you subtract dates in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31.


2 Answers

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

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();
}
like image 62
Jon Skeet Avatar answered Nov 20 '22 14:11

Jon Skeet


This version is JDK Calendar based:

public static void main(String[] args) throws Exception {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    Date d1 = f.parse("2012-01-01");
    Date d2 = f.parse("2012-02-02");
    int n = differenceInMonths(d1, d2);
    System.out.println(n);
}

private static int differenceInMonths(Date d1, Date d2) {
    Calendar c1 = Calendar.getInstance();
    c1.setTime(d1);
    Calendar c2 = Calendar.getInstance();
    c2.setTime(d2);
    int diff = 0;
    if (c2.after(c1)) {
        while (c2.after(c1)) {
            c1.add(Calendar.MONTH, 1);
            if (c2.after(c1)) {
                diff++;
            }
        }
    } else if (c2.before(c1)) {
        while (c2.before(c1)) {
            c1.add(Calendar.MONTH, -1);
            if (c1.before(c2)) {
                diff--;
            }
        }
    }
    return diff;
}
like image 21
Evgeniy Dorofeev Avatar answered Nov 20 '22 13:11

Evgeniy Dorofeev