这里推荐2种方式
依赖包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency>
1、@JsonFormat、@DateTimeFormat
用在属性上即可@JsonFormat(pattern = "yyyy-MM-dd") ,pattern 指定前端传递的日期格式(例如:sj:2018-1-26),
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(pattern = "yyyy-MM-dd")
//@DateTimeFormat(pattern = "yyyy-MM-dd") private Date sj;
PS:如果要精确到小时,则需要@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8"), 因为中国时间和标准时间有8个小时差
2@JsonSerialize
也可以自定义,写在属性上即可
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using=JsonDateSerializer.class) private Date sj;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class JsonDateSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator jsGener, SerializerProvider arg2) throws IOException, JsonProcessingException { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); String strDate = sf.format(value); jsGener.writeString(strDate); } }
这样前端不用再把时间 new date了, 后端返回也是格式后的时间,而不是时间戳了