@DateTimeFormat 接收不到时分秒,转换时报类型异常

报错信息如下

 nopaexpiretimeFailed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'nopaexpiretime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert
 from type [java.lang.String] to type [@com.baomidou.mybatisplus.annotation.TableField 
 @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '2020-12-21 19:45:27'; nested 
 exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-12-21 19:45:27]

其实是注解上的时间大小写的问题

@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

修改为大写即可

  • 结束

  • 补充

接收json数据时使用

@JsonFormat(pattern = "yyyy-MM-dd") 时间上添加此注解
@PostMapping(value = "" ,produces = "application/json;charset=UTF-8")
@RequestBody  接收json数据 

接收form数据时使用

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Valid   接收form数据  时间上作此注解即可

日常记录工作中遇到的问题,方便以后查阅

2021-01-28补充内容
在使用@JsonFormat注解时,需添加 timezone = “GMT+8”;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")

否则时间还是会差8个小时

@DateTimeFormat是一个Spring框架提供的注解,它可以用来指定日期时间格式,将前端传递的字符串类型的日期时间转换成Java中的日期时间类型。该注解可以用于方法参数、方法返回值以及JavaBean属性上。具体用法如下: 1. 方法参数使用@DateTimeFormat注解: ``` @RequestMapping("/test") public String test(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date date){ //TODO } ``` 在上述代码中,@RequestParam("date")用于指定请求参数的名称,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")用于指定日期时间格式,将前端传递的字符串类型的日期时间转换成Date类型。 2. 方法返回值使用@DateTimeFormat注解: ``` @RequestMapping("/test") @ResponseBody public Map<String,Object> test(){ Map<String,Object> result = new HashMap<>(); result.put("currentTime", new Date()); return result; } ``` 在上述代码中,@ResponseBody注解将返回结果转换成JSON格式,而Date类型默认转换成时间戳(Long类型)。如果需要指定日期时间格式,可以在Date类型上添加@DateTimeFormat注解,例如: ``` @RequestMapping("/test") @ResponseBody public Map<String,Object> test(){ Map<String,Object> result = new HashMap<>(); @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date currentTime = new Date(); result.put("currentTime", currentTime); return result; } ``` 3. JavaBean属性使用@DateTimeFormat注解: ``` public class User { private String name; @DateTimeFormat(pattern="yyyy-MM-dd") private Date birthday; // getter和setter方法 } ``` 在上述代码中,@DateTimeFormat注解用于指定日期时间格式,将前端传递的字符串类型的日期时间转换成Date类型。在实际应用中,可以通过Spring MVC的表单绑定功能,自动将前端提交的数据绑定到JavaBean对象上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值