Java Instant 创建和使用
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 对象,因此需要将结果保存到一个新的变量中。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2019-05-16 MySQL 树形结构 根据指定节点 获取其所在全路径节点序列
2019-05-16 MySQL 树形结构 根据指定节点 获取其所有父节点序列