使用@JsonFormat和@DateTimeFormat对Date格式化
实体类
package com.pojo;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
public class User {
private Long id;
private String username;//用户名
private String password;//密码
private String phone;//手机号
private String email;//邮箱
private Date created;//创建日期
private Date updated;//修改日期
public Long getId() { return id; }
public void setId(Long id) { this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getPassword() { return password;}
public void setPassword(String password) { this.password = password;}
public String getPhone() { return phone;}
public void setPhone(String phone) {this.phone = phone;}
public String getEmail() {return email;}
public void setEmail(String email) { this.email = email;}
public Date getCreated() {return created;}
public void setCreated(Date created) {this.created = created;}
public Date getUpdated() {return updated;}
public void setUpdated(Date updated) {this.updated = updated;}
}
一、@JsonFormat
控制器:
@RequestMapping("/getdate")
@ResponseBody
public TbUser getdate() {
TbUser user = new TbUser();
user.setId(1001l);
user.setUsername("zhangsan");
user.setPassword("1234567");
user.setPhone("15225969681");
user.setEmail("123@qq.com");
user.setUpdated(new Date());
user.setCreated(new Date());
return user;
}
访问控制器在浏览器中输出的json格式如下:
{"id":1001,"username":"zhangsan","password":"1234567","phone":"15212559252","email":"123@qq.com","created":1545288773904,"updated":"1545288773904"}
可见created、updated这两个属性值是时间戳并不是“yyyy-MM-dd HH:mm:ss”格式,那怎么把日期类型格式化成我们想要的类型呢,其实很简单只需要在实体类的属性上加上**@JsonFormat**注解就行了。
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date created;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updated;
@JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”)
**pattern:**是你需要转换的时间日期的格式
**timezone:**是时间设置为东八区(北京时间)
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别。
再次访问控制器,会发现在浏览器中输出的json格式就会变成我们指定的时间格式了。如下:
{"id":1001,"username":"zhangsan","password":"1234567","phone":"15225969681","email":"123@qq.com","created":2018-12-19 19:00:11,"updated":"2018-12-19 19:00:11"}
加上注解后将User对象转为json字符串时也是会按照注解中的格式进行转换
二、@DateTimeFormat
Index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>测试</title>
</head>
<body>
<form method="post" action="/getuser">
用户名:<input type="text" name="username"/></br>
密码:<input type="password" name="password"/></br>
手机:<input type="text" name="phone"/></br>
邮箱:<input type="text" name="email"/></br>
创建日期:<input type="datetime" name="created"/></br>
修改日期:<input type="datetime" name="updated"/></br>
<input type="submit" />
</form>
</body>
</html>
@RequestMapping(value="/getuser", method=RequestMethod.POST)
@ResponseBody
public TbUser getuser(TbUser user) {
System.out.println("-------------------------------");
System.out.println(user.toString());
System.out.println("-------------------------------");
return user;
}
当User实体类created、updated不加注解 @DateTimeFormat(pattern = “yyyy-MM-dd”) 时可以输入任意格式的日期如yyyy-MM-dd、yyyy/MM/dd…,后台仍会将接收到的字符串转换为Date,但如果加上@DateTimeFormat注解就只能按照注解后面的日期格式进行输入了。
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date created;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date updated;
控制台输出结果如下:
User [id=null, username=test, password=123, phone=12345678901, email=12112@qq.com, created=Thu Dec 20 00:00:00 CST 2012, updated=Thu Dec 20 00:00:00 CST 2012]
总结:
注解**@JsonFormat**:主要是控制后台到前台的时间格式
注解**@DateTimeFormat**:主要是限制前台到后台的时间格式
顺便分享一个json和Object互转的工具类,源码如下:
package com.common.utils;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}