Library contents

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

  1. Start with 2024-01-31
  2. Do this Add one calendar day
  3. Result 2024-02-01
January ends on day 31. The next day starts a new month.

Syntax

Groovy 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.

First output line2024-03-01
Lesson.groovy
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'
    }
}
Output
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

Advertisements

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?

Given28 February 2024 + 2 days
Worked result2024-03-01

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?

Given31 December 2026 + 1 day
Worked result2027-01-01