0

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!

hsz
  • 148,279
  • 62
  • 259
  • 315
  • 2
    @Niroshan The terrible `Date` classes both were supplanted years ago by the modern *java.time* classes years ago with the adoption of JSR 310. Suggesting their use in 2020 is poor advice. – Basil Bourque Jul 14 '20 at 02:43
  • This doesn’t seem well researched? There are some similar questions, for example [Java Date month difference](https://stackoverflow.com/questions/1086396/java-date-month-difference). [This answer by Kuchi](https://stackoverflow.com/a/28147750/5772882) wold probably have been helpful. – Ole V.V. Jul 14 '20 at 04:14

3 Answers3

2

java.time

Use java.time classes.

The Period::toTotalMonths method returns a long for the number of months elapsed along the entire span of time.

You asked for an int rather than a long. Rather than cast that long to your desired int, call Math.toIntExact. This method throws an exception if the resulting narrowing from the cast overflows.

int months =
    Math.toIntExact(
        Period.between
        (
            LocalDate.parse( "2019-05-31" ) ,
            LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
        )
        .toTotalMonths()
    )
;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

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
Marc
  • 2,738
  • 1
  • 17
  • 21
  • wow thank you so much...didn't know it was so simple :D –  Jul 14 '20 at 03:47
  • While it’s very unlikely for the result not to fit into an `int`, I find it best to scheck the assumption that it does. Use [`Math.toIntExact(Period.between(myDate,today).toTotalMonths())`](https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html#toIntExact(long)). – Ole V.V. Jul 14 '20 at 04:20
1

You can use the following approach

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateUtil{

    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String date = "2019-05-31";
        LocalDate localDate = LocalDate.parse(date, formatter);
        LocalDate now = LocalDate.now();

        long diff = ChronoUnit.MONTHS.between(localDate, now);

        System.out.println(diff);

    }
}

Prashanth D
  • 137
  • 1
  • 6