Java Instant 创建和使用

发布时间 2023-05-16 16:48:37作者: 龙凌云端

Java Instant 创建和使用


 

Java Instant 是一个日期和时间相关的类,它表示时间轴上的一个点,精确到纳秒。

在 Java 8 中引入了 Instant 类,可以方便地进行时间戳的操作和转换。

创建 Instant 实例可以通过以下几种方式:

 

1、使用 now() 方法获取当前时间的 Instant 对象

Instant now = Instant.now();

 

2、通过 ofEpochSecond() 或 ofEpochMilli() 方法从时间戳创建 Instant 对象

Instant instantFromSeconds = Instant.ofEpochSecond(1684216800);
Instant instantFromMillis = Instant.ofEpochMilli(1684216800000L);

 

3、通过解析字符串创建 Instant 对象

Instant instantFromString = Instant.parse("2022-05-16T12:34:56.789Z");

 

可以使用 toString() 方法将 Instant 对象格式化为 ISO 8601 格式的字符串。

System.out.println(now.toString()); // 输出:2022-05-16T12:34:56.789Z

 

Instant 对象支持数学运算符的操作,例如 plusSeconds()、plusMillis()、plusNanos()、minusSeconds()、minusMillis()、minusNanos() 等。

Instant now = Instant.now();
Instant future = now.plusSeconds(3600);
Instant past = now.minusMillis(500);

 

可以将 Instant 对象转换为其他日期时间相关类的对象,例如 LocalDateTime、ZonedDateTime 和 OffsetDateTime。

Instant now = Instant.now();
LocalDateTime localDateTime = LocalDateTime.ofInstant(now, ZoneId.systemDefault());
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, ZoneId.of("America/New_York"));
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(now, ZoneOffset.ofHours(8));

 

Instant 是一个不可变类,每个操作都会返回一个新的 Instant 对象,因此需要将结果保存到一个新的变量中。