核心是统一配置ObjectMapper:对Date用setDateFormat指定SimpleDateFormat并设时区,对java.time.*类型注册JavaTimeModule并添加对应DateTimeFormatter序列化器,同时可用@JsonFormat注解灵活控制单字段格式。

Java 中 JSON 序列化时规范日期时间输出格式,核心是统一配置序列化器对 java.util.Date、java.time.* 类型的处理方式,避免默认输出毫秒时间戳或不带时区的混乱字符串。
使用 Jackson(主流方案):全局配置日期格式
Jackson 是 Spring Boot 默认的 JSON 处理库。推荐在应用启动时通过 ObjectMapper 统一设置:
- 对
java.util.Date和Calendar:用setDateFormat()指定SimpleDateFormat - 对
java.time.*(如LocalDateTime、ZonedDateTime):注册JavaTimeModule并配置对应序列化器
示例(Spring Boot 中推荐写在配置类中):
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 统一日期格式:yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 指定时区,避免本地时区干扰
mapper.setDateFormat(sdf);
// 启用 Java 8 时间模块(支持 LocalDateTime 等)
JavaTimeModule timeModule = new JavaTimeModule();
// LocalDateTime 输出为 "2024-05-20 14:30:45"
timeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// LocalDate 输出为 "2024-05-20"
timeModule.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
// ZonedDateTime 或 Instant 可按需转为东八区字符串
timeModule.addSerializer(ZonedDateTime.class,
new ZonedDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSXXX")));
mapper.registerModule(timeModule);
return mapper;
}
用注解控制单个字段格式(灵活补充)
当只需个别字段定制格式,或无法修改全局配置时,可用 Jackson 注解:
立即学习“Java免费学习笔记(深入)”;
-
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8"):适用于Date、LocalDateTime等类型字段 - 注意:
timezone对LocalDateTime无效(它本就不含时区),仅对Date或ZonedDateTime生效
示例:
public class Order {
private Long id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate orderDate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSXXX")
private ZonedDateTime shippedAt;
}
避免常见坑点
-
别依赖默认行为:Jackson 默认把
Date序列为时间戳(long),LocalDateTime在未注册模块时会报错 -
时区要显式指定:服务器时区 ≠ 业务时区,不设
timezone或DateTimeFormatter时区,容易导致前端显示比预期快/慢 8 小时 -
前后端约定优先:格式如
yyyy-MM-dd HH:mm:ss要和前端解析逻辑一致;若前端用 moment.js 或 dayjs,建议带XXX(如+08:00)提升兼容性 -
Spring Boot 2.2+ 注意:默认已启用
JavaTimeModule,但仍需手动配置 pattern,否则LocalDateTime默认输出为 ISO 格式("2024-05-20T14:30:45")
FastJSON(旧项目可能用)简要说明
若使用 FastJSON(非推荐,尤其新项目),可通过:
- 全局:
JSON.defaultTimeZone = TimeZone.getTimeZone("GMT+8"); JSON.defaultDateFormat = "yyyy-MM-dd HH:mm:ss"; - 字段级:
@JSONField(format = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
但 FastJSON 存在安全与维护风险,建议逐步迁移到 Jackson。


















