当前时间:2019年10月24日。距离 JDK 14 发布时间(2020年3月17日)还有多少天?

// 距离JDK 14 发布还有多少天? LocalDate jdk14 = LocalDate.of(2020, 3, 17); LocalDate nowDate = LocalDate.now(); System.out.println("距离JDK 14 发布还有:"+nowDate.until(jdk14,ChronoUnit.DAYS)+"天");

JDK 8 已经在 2014年 3月 18日正式可用 ,距离现在已经 5年多时间过去了。5年时间里很多企业也都换上了 JDK 8,明年 3月份 Jdk14 也要来了,那么 Jdk 8 的新特性你真的用起来了吗?我准备写一个 Jdk 8开始的新特性介绍以及使用的系列文章,后续 Jdk 也会继续更新,你如果需要的话不妨关注下博客或者公众号。

1. 时间处理类

Jdk8 带来了全新的时间处理工具类,用于代替之前存在缺陷的时间处理。新的时间处理相比之前更加简单好用。

Jdk8 时间处理类

常用的类有以下几个类。

时间相关类 介绍
LocalDateTime 时间处理类,最高精确到纳秒
LocalDate 时间处理类,最高精确到天
DateTimeFormatter 时间格式化
ZoneId 时区设置类

2. 时间获取

使用不同的类可以获取不同精度的时间。

/**  * 时间获取 */ @Test public void nowTimeTest() {     // 当前精确时间     LocalDateTime now = LocalDateTime.now();     System.out.println("当前精确时间:" + now);     System.out.println("当前精确时间:" + now.getYear() + "-" + now.getMonthValue() + "-" + now.getDayOfMonth() + " " + now.getHour() + "-" + now.getMinute() + "-" + now.getSecond());      // 获取当前日期     LocalDate localDate = LocalDate.now();     System.out.println("当前日期:" + localDate);     System.out.println("当前日期:" + localDate.getYear() + "-" + localDate.getMonthValue() + "-" + localDate.getDayOfMonth());      // 获取当天时间     LocalTime localTime = LocalTime.now();     System.out.println("当天时间:" + localTime);     System.out.println("当天时间:" + localTime.getHour() + ":" + localTime.getMinute() + ":" + localTime.getSecond());      // 有时区的当前精确时间     ZonedDateTime nowZone = LocalDateTime.now().atZone(ZoneId.systemDefault());     System.out.println("当前精确时间(有时区):" + nowZone);     System.out.println("当前精确时间(有时区):" + nowZone.getYear() + "-" + nowZone.getMonthValue() + "-" + nowZone.getDayOfMonth() + " " + nowZone.getHour() + "-" + nowZone.getMinute() + "-" + nowZone.getSecond()); } 

获取到的时间:

当前精确时间:2019-10-24T00:26:41.724 当前精确时间:2019-10-24 0-26-41 当前日期:2019-10-24 当前日期:2019-10-24 当前精确时间(有时区):2019-10-24T00:26:41.725+08:00[GMT+08:00] 当前精确时间(有时区):2019-10-24 0-26-41 当天时间:00:26:41.725 当天时间:0:26:41

3. 时间创建

可以指定年月日时分秒创建一个时间类,也可以使用字符串直接转换成时间。

/**  * 时间创建  */ @Test public void createTime() {     LocalDateTime ofTime = LocalDateTime.of(2019, 10, 1, 8, 8, 8);     System.out.println("当前精确时间:" + ofTime);      LocalDate localDate = LocalDate.of(2019, 10, 01);     System.out.println("当前日期:" + localDate);      LocalTime localTime = LocalTime.of(12, 01, 01);     System.out.println("当天时间:" + localTime); }