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 对象,因此需要将结果保存到一个新的变量中。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值