天天看点

Java8 Instant 时间戳

在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