How can I calculate the difference between two dates(confirming some logic)?

In a tutorial I am watching,I am trying to calculate the difference between two dates. I need the initMonth and the finishMonth with the idea being to subtract the initMonth from the finishMonth and calculate the difference.

I can do something like this using the Calendar class(and then something similar with the finishMonth):

int initMonth = calendar.get(Calendar.MONTH);

...but the problem is that if the initMonth is May(for example) and the endMonth is January; when I subtract the endMonth from the initMonth I will get 1-5=-4--and I will have a negative difference. In order to solve this problem, the instructor came with the solution of multiplying the YEAR * 12 and then adding the month like this:

int initMonth = calendar.get(Calendar.YEAR) *12 + calendar.get(Calendar.MONTH);

However, this doesn't make any sense to me since the year will return something like 2021 * 12 + month to some extremely large number. My guess was that he meant MONTH so then we will get the months in the year plus the month. Would I be correct? I'm unsure, and wanted to confirm this logic.

Thank you in advance.

Answers 1

  • Your tutorial is obsolete by several years. Never use Calendar or Date class. Use only java.time classes.

    Apparently you want to calculate elapsed months.

    LocalDate then = LocalDate.of( 2020 , Month.MARCH ) ;
    LocalDate today = LocalDate.now() ;
    Period elapsed = Period.between ( then , today ) ;
    int months = elapsed.toMonths() ;
    

    Search Stack Overflow to learn more. This has been covered many times already.


Related Articles