如果要使用@JsonFormat这个注解的话,需要在项目中添加 jackson 相关的依赖包;因为 @JsonFormat 注解不是 Spring 自带的注解,所以使用该注解前需要添加 jackson 相关的依赖包。当然,如果是 SpringBoot 项目就不需要自己手动添加依赖了,因为在 spring-boot-start-web 下已经包含了 jackson 相关依赖。
如果要使用@DateTimeFormat这个注解的话,需要在项目中添加 springframework 相关的依赖包大家可以去这个网站搜索想要的依赖:https://mvnrepository.com@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
将后端返回给前端的日期时间进行格式化,pattern为转换后的格式,timezone为日期时间的时区
默认情况下timeZone为GMT(即标准时区),而北京是在东八区,所以会造成差8小时。
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime userCreateDate;@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
将前端传给后端的日期时间进行格式化,pattern为转换后的格式@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime userCreateDate;POST请求,我们一般会用@RequestBody接收JSON对象,如果对象里面有日期时间类型数据的话,我们可以使用 @JsonFormat注解进行格式化,它既可以对出参进行格式化,也可以对入参进行格式化GET请求参数都是拼接在URL后面的,则需要使用@DateTimeFormat对入参进行格式化,放到@RequestBody修饰的对象里面是无效的@JsonFormat是格式化json格式的。
@DateTimeFormat是格式化 key=value这种格式的。
需要取数据到前台,也需要前台数据传到后台,都需要进行时间格式的转换,可以同时使用 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date symstarttime;
SpringBoot的配置文件application.ymlspring:# Content-Type 为 application/json, @JsonFormat(优先级高) 或 spring.jackson.date-format jackson:date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8# Content-Type 为 application/x-www-form-urlencoded(普通表单上传)spring.mvc.date-format(优先级高) 或 @DatetimeFormat mvc:format:date-time: yyyy-MM-dd HH:mm:ssapplication.propertiesspring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.serialization.indent_output=true spring.jackson.serialization.fail_on_empty_beans=false到此这篇关于java日期时间格式化@JsonFormat与@DateTimeFormat的使用的文章就介绍到这了,更多相关java @JsonFormat与@DateTimeFormat内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:Java SimpleDateFormat中英文时间格式化转换详解Java日期时间格式化操作DateUtils 的整理Java date format时间格式化操作示例java正则表达式用法大全(深度好文) Java正则表达式matcher.group()用法代码Java正则表达式的基本用法和实例大全Java常用 Date 时间格式化、Calender日历、正则表达式的用法小结
