How to use LocalDateTime RequestParam in Spring? I get "Failed to convert String to LocalDateTime"

java-time, jsr310, spring, spring-boot, spring-mvc

Solution

TL;DR - you can capture it as a string with just `@RequestParam`, or you can have Spring additionally parse the string into a java date / time class via `@DateTimeFormat` on the parameter as well.

The `@RequestParam` is enough to grab the date you supply after the = sign. However, it comes into the method as a `String`. That is why it is throwing the cast exception.

There are a few ways to achieve this:

- Parse the date yourself, grabbing the value as a string.

@GetMapping("/test")
public Page<User> get(@RequestParam(value="start", required = false) String start){

    //Create a DateTimeFormatter with your required format:
    DateTimeFormatter dateTimeFormat = 
            new DateTimeFormatter(DateTimeFormatter.BASIC_ISO_DATE);

    //Next parse the date from the @RequestParam, specifying the TO type as a TemporalQuery:
   LocalDateTime date = dateTimeFormat.parse(start, LocalDateTime::from);
    
    //Do the rest of your code...
}

- Leverage Spring's ability to automatically parse and expect date formats:

@GetMapping("/test")
public void processDateTime(@RequestParam("start") 
                            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 
                            LocalDateTime date) {
        // The rest of your code (Spring already parsed the date).
}

Problem

I use Spring Boot and included `jackson-datatype-jsr310` with Maven: ``` <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.7.3</version> </dependency> ``` When I try to use a RequestParam with a Java 8 Date/Time type, ``` @GetMapping("/test") public Page<User> get( @RequestParam(value = "start", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start) { //... } ``` and test it with this URL: ``` /test?start=2016-10-8T00:00 ``` I get the following error: ``` { "timestamp": 1477528408379, "status": 400, "error": "Bad Request", "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException", "message": "Failed to convert value of type [java.lang.String] to required type [java.time.LocalDateTime]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '2016-10-8T00:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2016-10-8T00:00]", "path": "/test" } ```

Original source