Question

I am trying to check if a given interval is greater than 12 months using the following code:

public void testMonths() throws Exception {
    DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-mm");
    DateTime from = format.parseDateTime("2010-01");
    DateTime until = format.parseDateTime("2011-06");

    int months = Months.monthsBetween(from, until).getMonths();

    assertTrue(months > 12); // months = 12 for some reason.
}

Whenever the given interval is more then a year it will truncate the remaining months in the last year.

Input I've tried running:

15 months will return 12 months.
25 months will return 24 months.
36 months will return 36 months.
37 months will return 36 months.
Was it helpful?

Solution

The problem is your text pattern. "mm" means "minutes" not "months". If you change your pattern to "yyyy-MM" you'll find it works fine.

As a guiding principle the first thing I would do in a situation like this is try to isolate this to the smallest possible problem. So take text parsing and the complexity of DateTime (time zones etc) out of the equation:

LocalDate from = new LocalDate(2010, 1, 1);
LocalDate to = new LocalDate(2011, 6, 1);
int months = Months.monthsBetween(from, to).getMonths();

Now you'll see it's 17. So then the next step would be to go back to your original code, and print out the values of from and to... and you'll see something like:

2010-01-01T00:01:00.000Z
2011-01-01T00:06:00.000Z

Basically, avoid text parsing unless that's fundamentally part of the problem you're trying to diagnose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top