• 日期时间格式化 @JsonFormat与@DateTimeFormat


    如果要使用 @JsonFormat 这个注解的话,需要在项目中添加 jackson 相关的依赖包;
    因为 @JsonFormat 注解不是 Spring 自带的注解,所以使用该注解前需要添加 jackson 相关的依赖包。当然,如果是 SpringBoot 项目就不需要自己手动添加依赖了,因为在 spring-boot-start-web 下已经包含了 jackson 相关依赖
    在这里插入图片描述

    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.12.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    如果要使用 @DateTimeFormat 这个注解的话,需要在项目中添加 springframework 相关的依赖包

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>5.3.9version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    大家可以去这个网站搜索想要的依赖: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;
    
    • 1
    • 2

    @DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
    将前端传给后端的日期时间进行格式化,pattern为转换后的格式

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime userCreateDate;
    
    • 1
    • 2

    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;
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    SpringBoot的配置文件

    application.yml

    spring:
      # 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:ss
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    application.properties

    spring.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
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    02 本机搭建kubernetes学习环境kubemini
    在谷歌浏览器上注册账号--具有偶然性的成功
    C语言01、数据类型、变量常量、字符串、转义字符、注释
    MYSQL数据库细节详细分析
    .Net服务器性能监控,应用耗时统一监控平台
    双向TVS的符号及几个参数问题?
    【JAVA学习笔记】64 - 坦克大战1.4,限制坦克发射子弹,敌方击中我方坦克爆炸
    AutoIt Window Info 使用方法
    Arrays.asList的“坑”
    还在发愁PPT该怎么设计?看看这几个网站
  • 原文地址:https://blog.csdn.net/qq_39900031/article/details/126376519