問題場景:
在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
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
底層原理:https://www.cnblogs.com/yhtboke/p/5653542.html