@JsonFormat @DataTimeFormat 时间格式
创始人
2024-05-30 19:56:06
0

省流:用@JsonFormat即可

有时候会看到入参dto里,在时间类型的变量上用@DateTimeFormat,代码如下。

public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")private Date startDate;
}

这是为了入参传日期格式的值。即前端给后端传日期,如 {"startDate":"2022-01-01 01:02:02"}。如果没有@DateTimeFormat,会报错。

Invalid JSON input: 
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); 
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: 
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))

根据报错信息,while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',传入的值日期格式有问题。正确格式:2023-02-01T00:00:00.000+0800,即前端传参 {"startDate":"2023-02-01T00:00:00.000+0800"}。

所以有人会用@DataTimeFormat。

但@DataTimeFormat不如@JsonFormat好用。另,如果值是纯日期,例如2022-01-01,不需要用注解。

@DataTimeFormat用于前端传后端,@JsonFormat用于后端传前端,这种说法是错误的。@JsonFormat前传后、后传前都可以用。

@JsonFormat

com.fasterxml.jackson.annotation.JsonFormat;

public class XXXdto{@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private Date startDate;
}

@DataTimeFormat

org.springframework.format.annotation.DateTimeFormat

public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date startDate;
}

@JsonFormat 和 @DateTimeFormat 区别

@JsonFormat

@DateTimeFormat

转换前端传入后端的时间格式的值

约束后端响应前端的时间类型的值

×

数据类型(前端提交到后端)

必须json

用@RequestBody

必须form表单

不用@RequestBody

时区

×

响应给前端的时间会比实际时间晚8个小时

补充:

1.前端传值给后端,后端接收到的都是字符串。

2.前端传日期格式的值,如果形如yyyy-MM-dd,即{"startDate":"2023-01-02"},不需要用@DataTimeFormat和@JsonFormat,框架会帮你转。

参考

不要在听大坑们@DateTimeFormat 和 @JsonFormat只是前后端传参的区别了_*阿莫西林*的博客-CSDN博客

SpringBoot中时间格式化的5种方法!

相关内容

热门资讯

【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
Android|无法访问或保存... 这个问题可能是由于权限设置不正确导致的。您需要在应用程序清单文件中添加以下代码来请求适当的权限:此外...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
AsusVivobook无法开... 首先,我们可以尝试重置BIOS(Basic Input/Output System)来解决这个问题。...
ASM贪吃蛇游戏-解决错误的问... 要解决ASM贪吃蛇游戏中的错误问题,你可以按照以下步骤进行:首先,确定错误的具体表现和问题所在。在贪...
月入8000+的steam搬砖... 大家好,我是阿阳 今天要给大家介绍的是 steam 游戏搬砖项目,目前...