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