专业的JAVA编程教程与资源

网站首页 > java教程 正文

SpringBoot日期格式处理(springboot日期转换器)

temp10 2024-10-24 17:20:19 java教程 15 ℃ 0 评论


问题

Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-12-12 12:12'; nested exception is java.lang.IllegalArgumentException

分析

SpringMvc没有设置日期转换配置,直接把当成String类型强转Date类型!

SpringBoot日期格式处理(springboot日期转换器)

解决方案

第一种方法:

@DateTimeFormat 日期参数格式化注解

@RequestMapping(value = "test")
@ResponseBody
public Map<String,Object> test(@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date, @NumberFormat(pattern = "#,###.##")Double number){
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("data",date);
resultMap.put("number",number);
return resultMap;
}

第二种方法:

application.yml设置日期参数格式化配置:

spring:
  mvc:
    date-format: yyyy-MM-dd HH:mm:ss

返回格式化日期

第一种方法:

在实体类中Date属性上标记:@JsonFormatpattern:是你需要转换的时间日期的格式timezone:是时间设置为东八区,避免时间在转换中有误差

@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
private Date updateDate;

第二种方法:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8

@NumberFormat 注解 支持数字类型参数格式化格式

更多相关内容,Java&python,软件开发等学习资料,电子书及视频还有高级讲师公开课免费资源

需要的可以私聊小编发送【学习】二字


本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表