Groovy LocalDate.parse and plusDays
Groovy can use the JDK's LocalDate directly. Parse an ISO calendar date and add days without choosing a time zone.
A simple example
LocalDate.parse and plusDays
- Start with 2024-01-31
- Do this Add one calendar day
- Result 2024-02-01
Syntax
LocalDate.parse(text).plusDays(1)
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Move a reporting date across February
A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.
import java.time.LocalDate
import java.time.format.DateTimeParseException
['2024-02-29', '2023-02-29'].each { text ->
try {
println LocalDate.parse(text).plusDays(1)
} catch (DateTimeParseException ex) {
println 'invalid date'
}
}
2024-03-01 invalid date
An invalid leap day throws DateTimeParseException. Handle the invalid input separately so the report does not silently move it to a different date.
Java API documentation for LocalDate.parse and plusDays
Return a borrowed microscope
A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?
Send a year-end reminder
A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?