1. 概述
在本篇教程中,我们将介绍如何将 ZonedDateTime
对象转换为字符串,以及如何将字符串解析为 ZonedDateTime
实例。
2. 创建 ZonedDateTime
实例
首先,我们从创建一个 ZonedDateTime
对象开始。我们可以指定具体的年月日时分秒,也可以基于当前时间创建,或者从一个已有的 LocalDateTime
转换而来。
✅ 显式指定时间与时区:
ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC"));
✅ 获取当前时间并指定时区:
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC"));
✅ 基于 LocalDateTime
创建:
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));
3. ZonedDateTime
转换为字符串
要将 ZonedDateTime
转换为字符串,推荐使用 DateTimeFormatter
类来格式化输出。
⚠️ 格式化时区偏移量
可以使用格式符 "Z"
或 "X"
来显示时区偏移量:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss Z");
String formattedString = zonedDateTime.format(formatter);
输出示例:
02/01/2018 - 13:45:30 +0000
✅ 显示时区名称
使用 "z"
可以显示时区名称:
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss z");
String formattedString2 = zonedDateTime.format(formatter2);
输出示例:
02/01/2018 - 13:45:30 UTC
4. 字符串解析为 ZonedDateTime
反过来,我们也可以将符合格式的字符串解析为 ZonedDateTime
对象。
✅ 使用 ZonedDateTime.parse()
方法
该方法默认使用 ISO_ZONED_DATE_TIME
格式解析:
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-12-03T10:15:30+01:00");
如果字符串中不包含时区信息,则会抛出异常:
assertThrows(DateTimeParseException.class, () ->
ZonedDateTime.parse("2011-12-03T10:15:30", DateTimeFormatter.ISO_DATE_TIME));
✅ 两步转换法:先解析为 LocalDateTime
,再绑定时区
这种方法适用于你已经有一个不含时区的时间字符串:
ZoneId timeZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = LocalDateTime.parse("2011-12-03T10:15:30",
DateTimeFormatter.ISO_DATE_TIME).atZone(timeZone);
log.info(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
输出示例(假设系统时区为欧洲雅典):
INFO: 2011-12-03T10:15:30+02:00[Europe/Athens]
更多关于日期字符串解析的内容,可以参考这篇文章:Java 字符串转日期详解
5. 总结
本文我们学习了如何创建 ZonedDateTime
对象,并将其格式化为字符串;同时也介绍了如何将字符串解析回 ZonedDateTime
。这些操作在处理跨时区时间数据时非常实用。
完整代码示例可从 GitHub 获取:https://github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-datetime-string