• Index

Instant 类

Last updated: ... / Reads: 46 Edit

Instant 是 Java 8 中引入的一个类,用于表示时间戳(Timestamp)。它可以精确到纳秒级别,并且不依赖于任何特定的时区。

你可以使用Instant来记录某个具体时刻的时间。它与java.util.Date相比具有更高的精度和更好的可读性。 以下是一些关于Instant的常见操作:

创建一个Instant对象

Instant now = Instant.now(); // 获取当前的时间戳
Instant specificTime = Instant.ofEpochMilli(1632400000000L); // 使用毫秒数创建一个指定的时间戳

比较两个Instant对象的先后顺序

Instant instant1 = Instant.parse("2023-09-23T12:00:00Z");
Instant instant2 = Instant.parse("2023-09-23T13:00:00Z");
boolean isBefore = instant1.isBefore(instant2);
boolean isAfter = instant1.isAfter(instant2);

在Instant上进行加减操作

Instant instant = Instant.parse("2023-09-23T12:00:00Z");
Instant plusSeconds = instant.plusSeconds(60); // 增加60秒
Instant minusMinutes = instant.minusMinutes(30); // 减少30分钟

将Instant转换为其他类型

Instant instant = Instant.parse("2023-09-23T12:00:00Z");
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); // 转换为本地日期时间
Date date = Date.from(instant); // 转换为旧版的`java.util.Date`

Comments

Make a comment

  • Index