一、Instant简介
Instant类是Java8 中补充的一个 时间戳类,nstant 可以使用静态方法 now()或者of()方法来创建一个实例对象。
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());
控制台输出:
LocalDateTime 毫秒数:1539141733010
标签:Instant,获取,System,特性,毫秒,now,Java8 From: https://www.cnblogs.com/xiaweicn/p/17000386.html