Java 8 常用时间 api

发布时间:2019-11-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Java 8 常用时间 api脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Java 8 提供了一套新的时间 api ,比之前的 Calendar 类要简单明了很多。常用的有三个类 InstantLocalDateLocalDateTime , Instant 是用来表示时刻的,类似 Unix 的时间,表示从协调世界时1970年1月1日0时0分0秒起至现在的总秒数,也可以获取毫秒。LocalDate 表示一个日期,只有年月日,没有时分秒。LocalDateTime 就是年月日时分秒了。

Instant

public static void main(String[] args) {     Instant now = Instant.now();     System.out.PRintln("Now secoonds:" + now.getEpochSecond());     System.out.println("Now milli   :" + now.toEpochMilli()); }

输出当前时刻距离 1970年1月1日0时0分0秒 的秒和毫秒

Now secoonds:1541321299
Now milli :1541321299037

LocalDateTime

为了方便输出时间格式,Java8 提供了 DateTimeFormatter 类来替代之前的 SimpleDateFormat

public static void main(String[] args) {     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");     LocalDateTime now = LocalDateTime.now();     System.out.println("Now: " + now.format(formatter)); }

Now: 2018-11-04 16:53:09

LocalDateTime 提供了很多时间计算的方法,比如 加一个小时,减去一周,加上一天等等这样的计算,比之前的 Calendar 要方便许多。

public static void main(String[] args) {     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");     LocalDateTime now = LocalDateTime.now();     System.out.println("Now: " + now.format(formatter));      LocalDateTime nowPlusDay = now.plusDays(1);     System.out.println("Now + 1 day: " + nowPlusDay.format(formatter));      LocalDateTime nowMinusHours = now.minusHours(5);     System.out.println("Now - 5 hours: " + nowMinusHours.format(formatter)); }

Now: 2018-11-04 17:02:53
Now + 1 day: 2018-11-05 17:02:53
Now - 5 hours: 2018-11-04 12:02:53

LocalDateTime 还有 isAfterisBeforeisEqual 方法可以用来比较两个时间。LocalDate 的用法和 LocalDateTime 是类似的。

Instant 和 LocalDateTime 的互相转换

这俩的互相转换都要涉及到一个时区的问题。LocalDateTime 用的是系统默认时区。我们可以先把 LocalDateTime 转为 ZonedDateTime ,然后再转成 Instant

public static void main(String[] args) {     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");     LocalDateTime now = LocalDateTime.now();     System.out.println("Now: " + now.format(formatter));      Instant nowInstant = now.atZone(Zoneid.systemdefault()).toInstant();     System.out.println("Now mini seconds: " + nowInstant.toEpochMilli()); }

Now: 2018-11-04 17:19:16
Now mini seconds: 1541323156101

public static void main(String[] args) {     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");     Instant now = Instant.now();     System.out.println("Now mini seconds: " + now.toEpochMilli());       LocalDateTime nowDateTime = LocalDateTime.ofInstant(now, ZoneId.systemDefault());     System.out.println("Zone id: " + ZoneId.systemDefault().toString());     System.out.println("Now: " + nowDateTime.format(formatter)); }

Now mini seconds: 1541323844781
Zone id: Asia/Shanghai
Now: 2018-11-04 17:30:44

脚本宝典总结

以上是脚本宝典为你收集整理的Java 8 常用时间 api全部内容,希望文章能够帮你解决Java 8 常用时间 api所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。