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

Kery Hu picture Kery Hu · Oct 27, 2016 · Viewed 81k times · Source

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"
}

Answer

d0x picture d0x · Oct 2, 2017

You did everything correct :) . Here is an example that shows exactly what you are doing. Just Annotate your RequestParam with @DateTimeFormat. There is no need for special GenericConversionService or manual conversion in the controller. This blog post writes about it.

@RestController
@RequestMapping("/api/datetime/")
final class DateTimeController {

    @RequestMapping(value = "datetime", method = RequestMethod.POST)
    public void processDateTime(@RequestParam("datetime") 
                                @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateAndTime) {
        //Do stuff
    }
}

I guess you had an issue with the format. On my setup everything works well.