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

后端 未结 10 1440
小蘑菇
小蘑菇 2020-11-29 02:35

I use Spring Boot and included jackson-datatype-jsr310 with Maven:


    com.fasterxml.jackson.datatype         


        
10条回答
  •  既然无缘
    2020-11-29 02:41

    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.
    @GetMapping("/test")
    public Page 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:
    @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).
    }
    

提交回复
热议问题