在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
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());
控制台输出:
秒数: 毫秒数:86
LocalDateTime输出毫秒数的方式,比Instant多一步转换
LocalDateTime localDateTime = LocalDateTime.now(); //LocalDateTime转Instant Instant localDateTime2Instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); System.out.println("LocalDateTime 毫秒数:"+localDateTime2Instant.toEpochMilli());
控制台输出:
LocalDateTime 毫秒数:10
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211003.html原文链接:https://javaforall.net
