zoukankan      html  css  js  c++  java
  • @JsonFormat时间格式化注解使用

    原文地址:https://www.cnblogs.com/cangqinglang/p/10083661.html

    @JsonFormat注解是一个时间格式化注解,比如我们存储在mysql中的数据是date类型的,当我们读取出来封装在实体类中的时候,就会变成英文时间格式,而不是yyyy-MM-dd HH:mm:ss这样的中文时间,因此我们需要用到JsonFormat注解来格式化我们的时间。

    JsonFormat注解是jackson包里面的一个注解,因此在使用的时候需要引入fasterxml maven的jar包,如下所示。

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>

    引入fasterxml maven jar包之后,就可以在实体类属性上面使用@JsonFormat注解了,要注意的是,它只会在类似@ResponseBody返回json数据的时候,才会返回格式化的yyyy-MM-dd HH:mm:ss时间,你直接使用System.out.println()输出的话,仍然是类似“Fri Dec 01 21:05:20 CST 2017”这样的时间样式。

    复制代码
    package demo;
    import java.util.Date;
    import com.fasterxml.jackson.annotation.JsonFormat;
    
    public class Student {
        private int id;
        private String username;
            
        @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
        private Date createDate;
        
        //getter setter省略。。。
                
    }
    复制代码

    当我们这样@ResponseBody输出json数据的时候,@JsonFormat注解标识的date属性就会自动返回yyyy-MM-dd HH:mm:ss样式的时间了,例如。

    复制代码
    @PostMapping("/api/getStudent")
    @ResponseBody
    public Map<String,Object> findStudentById(Long stuId){
        Map<String,Object> resultMap = new HashMap<>();
        Student stu = StudentService.findStudentById(stuId);
        resultMap.put("result",stu);
        return resultMap;
    }
    复制代码
  • 相关阅读:
    事件的解密
    C#世界中的委托
    这次是C#中的接口
    完全二叉树的建立和翻转
    全排列的应用
    网易笔试-按位或运算
    柱状图的最大矩形--单调栈
    Linux将线程绑定到CPU内核运行
    Windows多线程与线程绑定CPU内核
    B+树介绍
  • 原文地址:https://www.cnblogs.com/eyesfree/p/12760806.html
Copyright © 2011-2022 走看看