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

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:

  1. parse the date yourself, grabbing the value as a string.
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...
  1. Leverage Spring’s ability to automatically parse and expect date formats:
public void processDateTime(@RequestParam("start") 
                            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 
                            LocalDateTime date) {
        // The rest of your code (Spring already parsed the date).

Leave a Comment