Home > OS >  Verifying if date from String is the last day of the month
Verifying if date from String is the last day of the month

Time:03-18

My input string date is as below:

String date = "1/31/2022";

I am transforming to a date:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

How do I know if my date is the last day of the month?

E.g.: for a String "1/31/2022" the output should be true. For 2/2/2023 it should be fast.

This is to run in Groovy in Jenkins but I believe I could use java as well

CodePudding user response:

SimpleDateFormat is obsolete. I'd use the modern stuff from the java.time package.

DateTimeFormatter MY_FORMAT = DateTimeFormatter.ofPattern("MM/dd/uuuu");

LocalDate x = LocalDate.parse("1/31/2022", MY_FORMAT);
if (x.getDayOfMonth() == x.lengthOfMonth()) {
  // it is the last day of the month
}
  • Related