ZetCode

Java ZonedDateTime

最后修改于 2024 年 7 月 13 日

在本文中,我们将展示如何在 Java 中使用 ZonedDateTime。

ZonedDateTime 表示日期和时间以及其时区信息。 与较旧的日期和时间类相比,它提供了一种更强大,更灵活的方式来处理日期和时间。

时区是地理区域,在该区域内使用相同的标准时间。 它有助于同步不同位置的时钟,确保同一区域的人们遵循一致的时间。

ZonedDateTime 的主要功能包括

默认时区

默认时区由 TimeZone.getDefault 确定。

Main.java
import java.util.TimeZone;

void main() {

    TimeZone def = TimeZone.getDefault();

    System.out.println(def.getDisplayName());
    System.out.println(def.toZoneId());
}

该程序确定我们的时区。 我们打印其显示名称和区域 ID。

$ java Main.java
Central European Standard Time
Europe/Bratislava

默认时区中的当前日期时间

ZonedDateTime.now 方法从系统时钟中获取默认时区中的当前日期时间。

Main.java
import java.time.ZonedDateTime;

void main() {

    var now = ZonedDateTime.now();
    System.out.println(now);
}

该示例打印默认时区中的当前日期时间。

$ java Main.java
2024-07-13T18:04:01.552994900+02:00[Europe/Bratislava]

从字符串解析 ZonedDateTime

parse 方法从文本字符串(例如 2007-12-03T10:15:30+01:00[Europe/Paris])获取 ZonedDateTime 的实例。 该字符串必须表示有效的日期时间,并使用 DateTimeFormatter.ISO_ZONED_DATE_TIME 进行解析。

Main.java
import java.time.ZonedDateTime;

void main() {

    var dt1 = "2024-07-13T18:04:01.552994900+02:00[Europe/Bratislava]";
    var dt2 = "2024-07-13T18:04:01.552994900+03:00[Europe/Moscow]";

    var zdt1 = ZonedDateTime.parse(dt1);
    System.out.println(zdt1);

    var zdt2 = ZonedDateTime.parse(dt2);
    System.out.println(zdt2);
}

该示例使用 ZonedDateTime.parse 解析两个日期时间字符串。

DateTimeFormatter

我们使用 DateTimeFormatter 来格式化 ZonedDateTime

Main.java
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

void main() {

    var now = ZonedDateTime.now();

    DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
    String nowf = now.format(formatter);

    System.out.println(nowf);
}

该示例使用 RFC_1123_DATE_TIME 格式格式化默认时区中的当前日期时间。

航班到达示例

我们正在从布拉迪斯拉发前往莫斯科。 我们想确定莫斯科时间的到达时间。

Main.java
import java.time.ZoneId;
import java.time.ZonedDateTime;


void main() {

    ZoneId baZone = ZoneId.of("Europe/Bratislava");

    // Set the expected arrival time in Bratislava (local time)
    ZonedDateTime expectedArrival = ZonedDateTime.of(2024, 7, 13,
            23, 0, 0, 0, baZone);

    // Convert to Moscow time zone (UTC+3)
    ZoneId moscowZone = ZoneId.of("Europe/Moscow");
    ZonedDateTime arrivalInMoscow = expectedArrival.withZoneSameInstant(moscowZone);

    System.out.println("Expected arrival in Bratislava: " + expectedArrival);
    System.out.println("Arrival in Moscow time: " + arrivalInMoscow);
}

该示例设置了 Europe/Bratislava 时区的到达时间。 使用 withZoneSameInstant,我们将其转换为 Europe/Moscow 时区。

$ java Main.java
Expected arrival in Bratislava: 2024-07-13T23:00+02:00[Europe/Bratislava]
Arrival in Moscow time: 2024-07-14T00:00+03:00[Europe/Moscow]

来源

Java ZonedDateTime - 语言参考

在本文中,我们使用了 Java ZonedDateTime。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 我自 2007 年以来一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有Java教程