jdk8 时间格式化 时分秒丢失_Jdk14 都要出了,Jdk8 的时间处理姿势还不了解一下?...

当前时间:2019年10月25日。距离 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 的新特性你真的用起来了吗?

1. 时间处理类

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

f2ecb54e9db0942cb86f9281684c0308.png

常用的类有以下几个类。

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

2. 时间获取

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

/** * 时间获取*/@Testpublic 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. 时间创建

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

/** * 时间创建 */@Testpublic 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);}

创建的时间:

当前精确时间:2019-10-01T08:08:08当前日期:2019-10-01当天时间:12:01:01

4. 时间转换

/*** 日期转换*/@Testpublic void convertTimeTest() { LocalDateTime parseTime = LocalDateTime.parse("2019-10-01T22:22:22.222"); System.out.println("字符串时间转换:" + parseTime); LocalDate formatted = LocalDate.parse("20190101
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值