16. Instant类
在JDK8中给我们新增一个Instant类(时间戳/时间线),内部保存了从1970年1月1日 00:00:00以来的秒和纳秒
Instant时间戳,可以用来统计时间戳
@Test
@DisplayName("Instant类")
public void test6() throws InterruptedException {
Instant now = Instant.now();
System.out.println("now = " + now);
// 获取从1970年1月1日 00:00:00 到现在的纳秒
int nano = now.getNano();
System.out.println("nano = " + nano);
Thread.sleep(5);
Instant now1 = Instant.now();
System.out.println("耗时 " + (now1.getNano() - now.getNano()));
}
now = 2023-04-05T13:43:52.485Z
nano = 485000000
耗时 15000000
Duration/Period
计算日期的差
在JDK8中提供了两个工具类Duration/Period,来计算及其时间差
Duration
:用来计算两个时间差(LocalTime)
Period
:用来计算两个日期差(LocalDate)
用来计算两个时间差(LocalTime)
@Test
@DisplayName("用来计算两个时间差(LocalTime)")
public void test7() {
LocalTime now1 = LocalTime.now();
System.out.println("now1 = " + now1);
LocalTime now2 = LocalTime.of(22, 00, 00);
// 通过Duration来计算时间差
Duration between = Duration.between(now2, now1);
System.out.println(between.toDays());
System.out.println(between.toHours());
System.out.println(between.toMinutes());
}
用来计算两个日期差(LocalDate)
@Test
@DisplayName("用来计算两个日期差(LocalDate)")
public void test8() {
LocalDate now1 = LocalDate.now();
LocalDate now2 = LocalDate.of(2022, 04, 06);
Period between = Period.between(now2, now1);
System.out.println(between.getYears());
System.out.println(between.getMonths());
System.out.println(between.getDays());
}
0
11
30