0

Need to identify number of months between two dates using java 8 but not getting proper number of months. Please find below program

public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.ENGLISH);
        YearMonth startDate = YearMonth.parse("12/31/2020", formatter);
        YearMonth endDate = YearMonth.parse("12/01/2021", formatter);
        
        System.out.println(startDate.plusYears(1) + " :: " + endDate + " :: " + startDate.plusYears(1).isBefore(endDate));
        
        long monthsBetween = ChronoUnit.MONTHS.between(startDate, endDate);
        System.out.println(monthsBetween);
}

Output ::

2021-12 :: 2021-12 :: false
12

So from above program we are getting 12 months between this 2 dates "12/31/2020" and "12/01/2021"

But actually no of months between above dates is 13 so how we are getting 12 instead of 13?

May be I am wrong but can someone please explain

Note : date format is MM/dd/yyyy

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • Could you please explain how your calculation looks that results in 13 months? How have you calculated that? – deHaar Jul 09 '21 at 07:18
  • Please check https://stackoverflow.com/questions/48950145/java-8-calculate-months-between-two-dates – Pramod Jul 09 '21 at 07:24

2 Answers2

0

The reason why you are getting 12 months because 'To' month is excluded from the counting. Here is the between method's implementation,

 //-----------------------------------------------------------------------
    @Override
    public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
        return temporal1Inclusive.until(temporal2Exclusive, this);
    }
pratap
  • 538
  • 1
  • 5
  • 11
0

The answer by pratap is fully correct. From the documentation of between():

The calculation returns a whole number, representing the number of complete units between the two temporals. For example, the amount in hours between the times 11:30 and 13:29 will only be one hour as it is one minute short of two hours.

Another way to say it is that the end month is not inclusive in the calculation. Which in turn means that the solution is to add one month to the end month:

    long monthsBetween = ChronoUnit.MONTHS.between(startDate, endDate.plusMonths(1));

Now output is what you wanted:

13

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161