什么是UTC?
UTC 是 Coordinated Universal Time 的缩写,中文叫:协调世界时。它是全球统一的时间基准。所有国家的时间,都是在 UTC 基础上加减偏移得到的,例如:
UTC 时间:2026-02-28 12:00
那么:
• 中国(UTC+8)→ 20:00
• 美国东部(UTC-5)→ 07:00
• UTC-12 → 00:00
为什么需要UTC?
在分布式系统中:
-
服务器可能在不同国家
-
用户在不同地区
-
日志需要统一时间基准
-
数据库要避免时区混乱
所以最佳实践是:服务器统一使用UTC,展示时再转为本地时区。
示例:
# linux使用date -u查看UTC
$ date
Thu Mar 12 15:39:46 CST 2026
$ date -u
Thu Mar 12 07:39:57 UTC 2026
#java中使用
Instant now = Instant.now();// 表示 UTC 时间线上的一个绝对时间点,它本身不包含时区信息
System.out.println(now); //2026-03-12T07:54:07.936329Z
ZonedDateTime displayTime = now.atZone(ZoneId.of("Asia/Shanghai")); //指定时区
System.out.println(displayTime.toString()); //2026-03-12T15:54:07.936329+08:00[Asia/Shanghai]
ZonedDateTime now1 = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(now1); //2026-03-12T15:54:07.936329+08:00[Asia/Shanghai]
时间戳和UTC的关系
时间戳本质是:从 1970-01-01 00:00:00 UTC 到当前时间的秒数或毫秒数。这个起点叫:Unix Epoch。它是基于 UTC 的,是一个绝对时间点。例如
UTC时间:1970-01-01 00:00:00
时间戳:0
UTC时间:1970-01-01 00:00:01
时间戳:1
时间戳转时间字符串
时间戳转时间字符串两种方法:
1)标准流程:(推荐)
timestamp → Instant → ZonedDateTime / LocalDateTime (指定时区)
通过Instant的atZone指定时区设置时区,如果不指定默认使用JVM默认时区,示例:
java
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
long timestamp = 1710230400000L;
Instant instant = Instant.ofEpochMilli(timestamp);
ZonedDateTime time = instant.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(time); //2024-03-12T16:00+08:00[Asia/Shanghai]
//格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String result = time.format(formatter);
System.out.println(result); //2024-03-12 16:00:00
//可以一步完成
String result =
Instant.ofEpochMilli(timestamp)
.atZone(ZoneId.of("Asia/Shanghai"))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
也可以通过DateTimeFormatter设置时区,例如:
java
DateTimeFormatter ft = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); //Asia/Shangha
String formattedDate = ft.format(Instant.ofEpochMilli(ts)); //2024-03-12 16:00:00
2)JDK8之前写法:(不推荐)
java.util.Date类本身是不带时区信息的,它仅存储自1970年1月1日00:00:00 GMT以来的毫秒数(时间戳)。Date对象在显示时会根据JVM本地时区(TimeZone)自动调整,所以如果服务器在UTC,而你想要UTC+8就会产生8小时误差。当然,可以在格式化的时候指定时区,例如:
java
#查看JVM默认时区:JVM Default TimeZone
System.out.println(TimeZone.getDefault().getID()); //JVM Default TimeZone: Asia/Shanghai
// 使用SimpleDateFormat处理时区
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shangha")); // 设置时区
System.out.println(sdf.format(date)); // 2024-03-12 16:00:00
什么是GMT
GMT是格林尼治时间,指位于英国伦敦郊区的皇家格林尼治天文台的标准时间。但由于较大的误差,现在基本不使用了。