Instant类是Java8中补充的一个时间戳类,nstant可以使用静态方法now()或者of()方法来创建一个实例对象,本文通过实例代码讲解Java8Instant时间戳,感兴趣的朋友跟随小编一起看看吧
说明
Instant 类 是Java8 中补充的一个 时间戳类。
相较于 System.currentTimeMillis()获取到【毫秒】,Instant 可以更为精确的获取到【纳秒】。
Instant 可以使用静态方法 now() 或者 of() 方法来创建一个实例对象。(案例代码中会有体现)
Instant 类的常用API 就是获取时间戳了
* Instant 类的 getEpochSecond() : 获取的是秒
* Instant 类的 toEpochMilli() : 获取的是毫秒,同 System.currentTimeMillis()
* Instant 类的 getNano() : 获取的是纳秒,更精确了
同时,Instant 类还是 Java8 中 提供的新的 日期时间类LocalDateTime 与 原来的 java.util.Date 类之间转换的桥梁。
在java.util.Date类与LocalDate、LocalDateTime类之间转换中 均可以通过Instant作为中间类完成转换,Instant的使用还是比较方便的,下面介绍Instant的使用。
一、创建Instant实例
Instant now = Instant.now();
System.out.println("now:"+now);
控制台输出:
now:2018-07-09T08:59:08.853Z
注意:通过这种方式获取的时间戳与北京时间相差8个时区,需要修正为北京时间,通过查看源代码发现Instant.now()使用等是UTC时间Clock.systemUTC().instant()。LocalDate、LocalDateTime 的now()方法使用的是系统默认时区 不存在Instant.now()的时间问题。
###解决方法
增加8个小时
Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("now:"+now);
控制台输出:
now:2018-07-09T16:58:48.188Z
二、Instant获取long类型的10位秒数、13位毫秒数
Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("秒数:"+now.getEpochSecond());
System.out.println("毫秒数:"+now.toEpochMilli());
控制台输出:
秒数:1539170157
毫秒数:1539170157886
LocalDateTime输出毫秒数的方式,比Instant多一步转换
LocalDateTime localDateTime = LocalDateTime.now();
//LocalDateTime转Instant
Instant localDateTime2Instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println("LocalDateTime 毫秒数:"+localDateTime2Instant.toEpochMilli());
控制台输出:
LocalDateTime 毫秒数:1539141733010
到此这篇关于Java8 Instant 时间戳的文章就介绍到这了,更多相关Java8 Instant 时间戳内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:Java8 Instant 时间戳实例讲解
- JSP页面间传值问题实例简析 2023-08-03
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- JSP 制作验证码的实例详解 2023-07-30
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java实现顺序表的操作详解 2023-05-19
- 深入了解Spring的事务传播机制 2023-06-02
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Java中的日期时间处理及格式化处理 2023-04-18
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17