后台LocalDateTime参数的接收问题(Failed to convert value of type 'java.lang.String' to required type 'java.tim...

在SpringMVC后台处理中,当尝试用@RequestParam接收前端传来的LocalDateTime类型时,会遇到转换异常。解决方案是使用@DateTimeFormat注解指定时间格式。同时,@JsonFormat注解可用于从数据库取出时间数据并按特定格式返回给前端,如指定pattern为'yyyy-MM-dd'和timezone为'GMT+8',确保时间转换准确。

在SpringMVC中通过@RequestParam接收jdk8的LocalDateTime时间类型的时候

前端通过传入

后台接收方式

会出现如下异常:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: 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 java.time.LocalDateTime] for value '2018-11-11 12:12:12'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-11-11 12:12:12]

解决方式:

是通过@DateTimeFormat注解,去解析前端传入的时间格式字符串然后转化成LocaDateTime的时间类型

那么同时可以说一下

@JsonFormat:他和@DateTimeFormat正好对应关系,如果我们从DB中取得时间类型数据,想传回前端,并且规定格式,那么就可以使用@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")

 pattern:是你需要转换的时间日期的格式

 timezone:是时间设置为东八区,避免时间在转换中有误差

 提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别

 

转载于:https://www.cnblogs.com/h-java/p/10318435.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值