📜  Java中的 Instant ofEpochSecond() 方法及示例(1)

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

Java 中的 Instant ofEpochSecond() 方法及示例

在 Java 中,Instant 类用于表示时间戳,即自协调世界时(UTC)1970 年 1 月 1 日午夜以来的秒数。Instant 类提供了多个方法来创建时间戳,其中之一是 ofEpochSecond() 方法。本文将介绍该方法的用法及示例。

方法介绍

Instant 类的 ofEpochSecond() 方法用于创建时间戳,以秒为单位。该方法有两个重载版本:

1. ofEpochSecond(long epochSecond)

该方法接受一个 long 类型参数 epochSecond,表示自 UTC 1970 年 1 月 1 日午夜以来的秒数。它返回一个 Instant 实例,表示给定的时间戳。

2. ofEpochSecond(long epochSecond, long nanoAdjustment)

该方法接受两个 long 类型参数,分别表示自 UTC 1970 年 1 月 1 日午夜以来的秒数和所需的额外纳秒数。它返回一个 Instant 实例,表示给定的时间戳。如果 nanoAdjustment 的绝对值大于 999,999,999,那么将其四舍五入到最接近的合法值。

示例

下面是使用 ofEpochSecond() 方法创建时间戳的示例代码:

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        // 创建当前时间的时间戳
        Instant now = Instant.now();
        System.out.println("Current timestamp: " + now);

        // 创建自 1970 年 1 月 1 日午夜以来的时间戳
        Instant epoch = Instant.ofEpochSecond(0);
        System.out.println("Epoch timestamp: " + epoch);

        // 创建指定时间的时间戳
        Instant custom = Instant.ofEpochSecond(1609459200);
        System.out.println("Custom timestamp: " + custom);

        // 创建带有纳秒调整的时间戳
        Instant nano = Instant.ofEpochSecond(1609459200, 500_000_000);
        System.out.println("Timestamp with nano adjustment: " + nano);
    }
}

上述代码创建了四个不同的时间戳,分别是当前时间的时间戳、自 1970 年 1 月 1 日午夜以来的时间戳、指定时间的时间戳以及带有纳秒调整的时间戳。运行结果如下:

Current timestamp: 2021-01-03T10:13:38.189160Z
Epoch timestamp: 1970-01-01T00:00:00Z
Custom timestamp: 2021-01-01T00:00:00Z
Timestamp with nano adjustment: 2021-01-01T00:00:00.500Z

可以看到,当前时间的时间戳使用了 Instant 类的 now() 方法创建,而其他三个时间戳都使用了 ofEpochSecond() 方法创建。对于带有纳秒调整的时间戳,它的纳秒部分为 500,000,000,即 0.5 秒。