Search code examples
groovyruntimeexception

Groovy: How to manually create a date? - GroovyRuntimeException


I want to export some data from a web api using Groovy. Therefore I want to manually set a date from which I want to begin. For example I want to start from 31th of december 2020.

Therefore I used this code:

import java.time.LocalDateTime;
LocalDateTime fromDate = new LocalDateTime(2020, 12, 31, 10, 00);

When executing the script I get a GroovyRuntimeException:

groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.time.LocalDateTime(Integer, Integer, Integer, Integer, Integer)

Solution

  • LocalDateTime does not have a public constructor. Use one of the many factory of() methods:

    LocalDateTime fromDate = LocalDateTime.of(2020, 12, 31, 10, 0, 0)
    //or
    LocalDateTime fromDate = LocalDateTime.of(LocalDate.of(2020, 12, 31), 
                                              LocalTime.of(10, 0, 0))
    //etc.