Java8 Instant 时间戳

2022年12月4日09:58:44

在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
  • 作者:springinwinter_4all
  • 原文链接:https://blog.csdn.net/chunzhilianxue/article/details/80974202
    更新时间:2022年12月4日09:58:44 ,共 1032 字。