Java中将时间戳转为格式化日期字符串应优先使用java.time API:先用Instant.ofEpochMilli(ts)转瞬时,再atZone指定时区(如"Asia/Shanghai"),最后用DateTimeFormatter.format格式化;注意时间戳单位为毫秒、显式指定时区以避免systemDefault依赖。

Java 中将时间戳转为格式化日期字符串,核心是用 SimpleDateFormat(旧 API)或 DateTimeFormatter(推荐的现代 API)配合对应的时间类处理。关键在于:时间戳单位是毫秒,且需注意时区。
使用现代 API(推荐:LocalDateTime / ZonedDateTime + DateTimeFormatter)
Java 8 引入了 `java.time` 包,线程安全、语义清晰、默认支持时区,应优先使用。
-
如果时间戳代表“系统默认时区的本地时间”:先转为
ZonedDateTime,再格式化
long timestamp = 1717027200000L; // 比如 2024-05-31 00:00:00 GMT+08:00
Instant instant = Instant.ofEpochMilli(timestamp);
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String result = zdt.format(formatter); // 输出:2024-05-31 00:00:00(按本机时区)
-
如果明确需要某一时区(如 UTC 或 GMT+8):指定
ZoneId更可靠
ZonedDateTime utcTime = instant.atZone(ZoneId.of("UTC"));
String utcStr = utcTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
使用旧 API(SimpleDateFormat,仅兼容老项目)
SimpleDateFormat 非线程安全,需每次创建新实例或加锁;它直接配合 Date 使用。
- 时间戳毫秒值可直接传给
new Date(long) -
SimpleDateFormat默认使用 JVM 默认时区,建议显式设置
long timestamp = 1717027200000L;
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 显式设时区
String result = sdf.format(date);
常见坑与注意事项
- 时间戳单位是毫秒,不是秒——若原始数据是秒级(如 Unix 时间戳),要乘以 1000
- 不同时区下格式化结果不同,
systemDefault()依赖运行环境,生产环境建议固定时区(如ZoneId.of("Asia/Shanghai")) -
DateTimeFormatter是不可变且线程安全的,可复用;SimpleDateFormat不可复用在多线程中 - 模式字母大小写敏感:
MM是月份,mm是分钟;YYYY是“周所属年”,一般用yyyy
一句话总结写法(推荐)
用 Instant.ofEpochMilli(ts).atZone(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),清晰、安全、可控。
立即学习“Java免费学习笔记(深入)”;


















