Search code examples
javadatedate-formattingmonthcalendar

Get the number of months beetween a date and today in JAVA


I'm trying to get the number of months between a given date in a String format ("2019-05-31"), sent as a parameter, and today : 2020-07-13. In this example it would be 13 month.

I want to put the answer in an int variable.

Is there an easy way to do it?

Thank you very much!


Solution

  • Since Java 1.8:

    LocalDate today = LocalDate.now();
    LocalDate myDate = LocalDate.parse("2019-05-31");
    int months = (int) Period.between(myDate,today).toTotalMonths();
    System.out.println(months); // output: 13