-1

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

DevOps QA
  • 59
  • 8
  • Do yourself a great favour. Immediately stop using `SimpleDateFormat` and `Date`. In this case use `LocalDate` and `DateTimeFormatter` both from java.time, the modern Java date and time API. – Ole V.V. Mar 17 '22 at 17:17

1 Answers1

6

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

Use single character M and d if not padding single-digit values with a leading zero.

DateTimeFormatter MY_FORMAT = DateTimeFormatter.ofPattern("M/d/uuuu");

LocalDate x = LocalDate.parse("1/31/2022", MY_FORMAT);
if (x.getDayOfMonth() == x.lengthOfMonth()) {
  // it is the last day of the month
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • 2
    There is a mismatch between input and format, `MM` should be changed or input should have leading zeros. – Eritrean Mar 17 '22 at 17:08
  • The question at https://stackoverflow.com/questions/27571377/datetimeformatter-support-for-single-digit-day-of-month-and-month-of-year addresses the item that @Eritrean mentioned. I think as written in the answer, that code probably throws an exception. – Jeff Scott Brown Mar 17 '22 at 17:40
  • Thank you. I just had to replace MM/dd/uuuu to M/d/uuuu for it to work. Thank you – DevOps QA Mar 17 '22 at 18:06
  • 1
    I corrected the format problem in this Answer, as mentioned in these Comments: `M/d/uuuu` rather than `MM/dd/uuuu`. – Basil Bourque Mar 17 '22 at 20:35
  • Good Answer. Another route is using [`YearMonth::atEndOfMonth`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/YearMonth.html#atEndOfMonth()). – Basil Bourque Mar 17 '22 at 20:37