java 新日期 api_【Java8新特性】Java新的时间日期API

Java8引入了新的时间和日期API,非常方便好用。在这里记录下新的api在工作中常用的操作

一、获取当前时间和日期

1.获取当前日期

LocalDate now = LocalDate.now();

System.out.println(now);

System.out.println(now.getYear() + "," + now.getMonthValue() + "," + now.getDayOfMonth());

// 输出结果:

2020-09-22

2020,9,22

2.获取当前时间

LocalTime nowTime = LocalTime.now();

System.out.println(nowTime);

// 输出结果:

00:05:45.404

3.获取当前的日期时间

LocalDateTime nowDateTime = LocalDateTime.now();

System.out.println(nowDateTime);

// 输出结果:

2020-09-22T00:05:45.404

二、构造时间和日期

LocalDate localDate = LocalDate.of(2020, 9, 25);

LocalDateTime localDateTime = LocalDateTime.of(2020, 9, 25, 21, 50);

System.out.println(localDate);

System.out.println(localDateTime);

// 输出结果:

2020-09-25

2020-09-25T21:50

三、时间、日期加减操作和比较

1.加减年月日小时

LocalDateTime nowDateTime = LocalDateTime.now();

System.out.println(nowDateTime);

System.out.println(nowDateTime.plusDays(1));

System.out.println(nowDateTime.minusDays(1));

System.out.println(nowDateTime.plus(1, ChronoUnit.DAYS));

System.out.println(nowDateTime.plus(1, ChronoUnit.MONTHS));

// 输出结果:

2020-09-26T21:40:50.896

2020-09-27T21:40:50.896

2020-09-25T21:40:50.896

2020-09-27T21:40:50.896

2020-10-26T21:40:50.896

2.时间比较

LocalDate day1 = LocalDate.of(2019, 9, 25);

LocalDate day2 = LocalDate.of(2020, 9, 25);

System.out.println(day1.isBefore(day2));

System.out.println(day1.isAfter(day2));

// 输出结果:

true

false

3.计算两个时间相差的年月日

LocalDate day1 = LocalDate.of(2019, 9, 25);

LocalDate day2 = LocalDate.of(2020, 9, 25);

System.out.println(ChronoUnit.DAYS.between(day1, day2));

System.out.println(ChronoUnit.MONTHS.between(day1, day2));

System.out.println(ChronoUnit.YEARS.between(day1, day2));

// 输出结果:

366

12

1

四、字符串与时间、日期互转

1. 时间转String

LocalDateTime nowDateTime = LocalDateTime.now();

System.out.println(nowDateTime);

System.out.println(nowDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

// 输出结果:

2020-09-26T19:51:17.798

2020-09-26 19:51:17

2. String转时间

String nowDay = "20200926";

System.out.println(LocalDate.parse(nowDay, DateTimeFormatter.ofPattern("yyyyMMdd")));

String nowTime = "20200926 19:57:38";

System.out.println(LocalDateTime.parse(nowTime, DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss")));

// 输出结果:

2020-09-26

2020-09-26T19:57:38

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值