ZetCode

Java Instant

最后修改日期:2024 年 7 月 10 日

在本文中,我们将展示如何使用 Instant 在 Java 中定义时间点。

Instant 表示时间轴上的特定时间点。它类似于永无止境的线上的一个点。 与其他日期和时间类不同,Instant 本身不包含时区信息。 而是将时间度量为自特定时间点(称为 epoch)以来经过的秒数和纳秒数。

epoch 是 1970 年 1 月 1 日协调世界时 (UTC) 00:00:00。 正 Instant 值表示 epoch 之后的时间,而负值表示之前的时间。

Instant 的常见用例包括:

当前时间戳

我们使用 Instant.now 获取当前时间戳。

Main.java
import java.time.Instant;

void main() {

    var timestamp = Instant.now();
    System.out.println("The current timestamp: " + timestamp);
}

该示例打印当前时间戳。

$ java Main.java
The current timestamp: 2024-07-10T14:37:39.890616200Z

Unix 时间

Unix 时间(也称为 POSIX 时间或 epoch 时间)是一个用于描述时间点的系统,定义为自协调世界时 (UTC) 1970 年 1 月 1 日星期四 00:00:00 以来经过的秒数,减去此后发生的闰秒数。

Main.java
import java.time.Instant;

void main() {

    Instant now = Instant.now();
    
    long unixTime = now.toEpochMilli();
    System.out.println(unixTime);
}

我们计算当前 Unix 时间(以毫秒为单位)。

$ java Main.java
1720623471356

plus/minus 方法

plus/minus 方法可用于将日期时间单位添加到 instant。

Main.java
import java.time.Instant;
import java.time.temporal.ChronoUnit;

void main() {

    var timestamp = Instant.now();

    var res = timestamp.plus(5, ChronoUnit.DAYS);
    System.out.println(res);

    res = timestamp.plusSeconds(78566);
    System.out.println(res);

    res = timestamp.minus(57, ChronoUnit.HOURS);
    System.out.println(res);
}

该示例获取当前 instant 并添加 5 天、78566 秒,并减去 57 小时。

$ java Main.java
2024-07-15T14:42:46.830593700Z
2024-07-11T12:32:12.830593700Z
2024-07-08T05:42:46.830593700Z

格式化 Instant

我们使用 DateTimeFormatter 来格式化 instants。

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

void main() {

    var timestamp = Instant.now();
    System.out.println(timestamp);

    DateTimeFormatter df1 = DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("UTC"));
    System.out.println(df1.format(timestamp));

    DateTimeFormatter df2 = DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));;

    System.out.println(df2.format(timestamp));
}

由于 Instant 不包含日期或时间组件,仅表示一个时间点,我们使用 withZone(ZoneId.of("UTC")) 添加时区。

$ java Main.java
2024-07-10T14:51:09.957078500Z
2024-07-10T14:51:09.9570785Z[UTC]
Wed, 10 Jul 2024 14:51:09 GMT

转换为 LocalDateTime

在下面的示例中,我们将展示如何将 Instant 转换为 LocalDateTime

Main.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

void main() {

    Instant now = Instant.now();

    LocalDateTime localDateTimePST = LocalDateTime.ofInstant(now, ZoneId.of("Europe/Bratislava"));
    System.out.println("Current time in Bratislava: " + localDateTimePST);
}

在该示例中,我们将 Instant 转换为特定时区(欧洲/布拉迪斯拉发)的 LocalDateTime

$ java Main.java
Current time in Bratislava: 2024-07-10T16:54:46.319805200

来源

Java Instant - 语言参考

在本文中,我们使用了 Java Instant 来定义时间点。

作者

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

列出所有Java教程