springboot之Date格式化

问题场景:

  在springboot应用中,@RestController层注解的json默认序列化中,日期格式默认为:2018-06-17T07:24:07.430+0000。

  日常需求中,往往需要将日期转化为

修改方法:

  方法一:
    在apllication.properties加入下面配置
    #时间戳统一转换
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

    #这个是时区,一定要加,否则会默认为格林尼治时间,即少8小时
    spring.jackson.time-zone=GMT+8
  
  方法二:
    在bean对象上加上
    @JsonFormat(timezone = "GMT+8", pattern = "yyyyMMddHHmmss")
    private Date createTime;
  

示例代码

  controller层

   /**
     * <p>一个返回json的例子</p>
     * */
    @RequestMapping("/json")
    public DemoVO getDemo(){
        DemoVO demoVO = new DemoVO();
        demoVO.setDemoName("demoName");
        demoVO.setDemoValue("测试");
        demoVO.setCurDate(new Date());
        return demoVO;
    }

  application.properties配置文件

spring.jackson.date-format=yyyy-MM-dd HH\:mm\:ss
spring.jackson.time-zone=GMT+8
扫描二维码关注公众号,回复: 1614786 查看本文章

  DemoVO.java文件

/**
 * @Description 一个样例值对象
 * @Author chendeming
 * @Date 2018/6/17 下午1:50
 * @Version 1.0
 **/
public class DemoVO {

    private String DemoName;
    private String DemoValue;
//    @JsonFormat(timezone = "GMT+8", pattern = "yyyyMMddHHmmss")//这里放开,就按这里的格式走
    private Date curDate;

    public String getDemoName() {
        return DemoName;
    }

    public void setDemoName(String demoName) {
        DemoName = demoName;
    }

    public String getDemoValue() {
        return DemoValue;
    }

    public void setDemoValue(String demoValue) {
        DemoValue = demoValue;
    }

    public Date getCurDate() {
        return curDate;
    }

    public void setCurDate(Date curDate) {
        this.curDate = curDate;
    }

    @Override
    public String toString() {
        return "DemoVO{" +
                "DemoName='" + DemoName + '\'' +
                ", DemoValue='" + DemoValue + '\'' +
                ", curDate=" + curDate +
                '}';
    }
}

 更多格式化方法:https://blog.csdn.net/ldj0816/article/details/52681153

猜你喜欢

转载自www.cnblogs.com/chendeming/p/9193017.html
今日推荐