最近用JSON处理Date类型的对象时,发现会变成时间戳的形式,如下图。
这里顺便说一下时间戳的含义,时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起到现在的总秒数。是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。
解决方法:关闭时间戳功能,并设置日期格式,这样就能显示出正确的日期格式了。
@Controller
public class UserController {
@RequestMapping("/test")
@ResponseBody
public String json() throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
//关闭时间戳的功能
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//转换时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//让mapper指定时间日期格式为SimpleDateFormat
mapper.setDateFormat(sdf);
Date date = new Date();
//将日期对象转换为json字符串格式