📜  java.time.ZonedDateTime类(1)

📅  最后修改于: 2023-12-03 15:31:35.108000             🧑  作者: Mango

Java.time.ZonedDateTime 类介绍

Java.time.ZonedDateTime 类提供了表示日期、时间和时区的 API。它是线程安全的,具有不可变性和可比性。ZonedDateTime 类继承自 java.time.LocalDateTime 类,并添加了时区信息。

1. 创建 ZonedDateTime 对象

我们可以通过以下方式创建一个 ZonedDateTime 对象:

1.1. 从 LocalDateTime 对象创建
LocalDateTime localDateTime = LocalDateTime.of(2021, 10, 1, 10, 10);
ZoneId zoneId = ZoneId.systemDefault(); // 获取默认时区 ID
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
1.2. 从 Instant 对象创建
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
1.3. 解析字符串创建
String strDateTime = "2021-10-01T10:10:10+08:00[Asia/Shanghai]";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(strDateTime);
2. ZonedDateTime 常用方法

ZonedDateTime 类包含了很多方法用于操作时间和日期,以下是一些常用方法:

2.1. 转换时区
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.systemDefault());
ZoneId newZoneId = ZoneId.of("America/New_York");
ZonedDateTime newDateTime = zonedDateTime.withZoneSameInstant(newZoneId);
2.2. 比较时间先后
ZonedDateTime dateTime1 = ZonedDateTime.of(2021, 10, 1, 10, 10, 10, 0, ZoneId.of("Asia/Shanghai"));
ZonedDateTime dateTime2 = ZonedDateTime.of(2021, 10, 1, 9, 10, 10, 0, ZoneId.of("Asia/Shanghai"));
if (dateTime1.isAfter(dateTime2)) {
    System.out.println(dateTime1 + "在" + dateTime2 + "之后");
}
2.3. 格式化日期
ZonedDateTime dateTime = ZonedDateTime.of(2021, 10, 1, 10, 10, 10, 0, ZoneId.of("Asia/Shanghai"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss VV");
String strDateTime = dateTime.format(formatter); // 2021年10月01日 10:10:10 Asia/Shanghai
3. 总结

ZonedDateTime 类是一个非常重要的日期时间 API,它不仅提供了一些常用的方法,还支持日期时间和时区的转换、比较和格式化等操作。如果你正在编写需要处理日期和时间的 Java 应用程序,那么不要忘记使用 ZonedDateTime 类。