如:“2021-08-12 22:58:56”
// 返回格式化日期对象
@RequestMapping("/json4")
public String json4() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// 不使用时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf);
// 设置 日期格式
mapper.setDateFormat(sdf);
Date date = new Date();
// 设置字符串对象
String str = mapper.writeValueAsString(date);
return str;
}
}
该博客介绍了如何在Java中避免使用时间戳来格式化日期,并提供了示例代码展示如何利用`ObjectMapper`和`SimpleDateFormat`将日期转换为指定格式的字符串。通过设置`SerializationFeature.WRITE_DATES_AS_TIMESTAMPS`为`false`,可以确保日期以易读的字符串形式输出。

被折叠的 条评论
为什么被折叠?



