您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime”

如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime”

您可以使用just捕获它为字符串@RequestParam,也可以让Spring也通过@DateTimeFormat参数另外将字符串解析为java日期/时间类。

@RequestParam足以抓住你等号(=)后提供的日期,但是,它涉及到的方法作为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...

}

利用Spring的自动分析和期望日期格式的能力:

@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). }

Java 2022/1/1 18:23:24 有602人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶