LocalDateTime.now()怎么相减
时间: 2024-04-28 17:17:16 浏览: 92
c#中DateTime.Now函数的使用详解
5星 · 资源好评率100%
LocalDateTime.now()是Java 8中的一个日期时间类,表示当前的本地日期和时间。如果要计算两个LocalDateTime对象之间的时间差,可以使用Duration类或者ChronoUnit类来实现。
下面是使用Duration类计算时间差的示例代码:
```
LocalDateTime dateTime1 = LocalDateTime.now();
LocalDateTime dateTime2 = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
Duration duration = Duration.between(dateTime1, dateTime2);
long seconds = duration.getSeconds();
long minutes = duration.toMinutes();
long hours = duration.toHours();
long days = duration.toDays();
System.out.println("时间差(秒):" + seconds);
System.out.println("时间差(分钟):" + minutes);
System.out.println("时间差(小时):" + hours);
System.out.println("时间差(天):" + days);
```
另外,也可以使用ChronoUnit类来计算时间差,如下所示:
```
LocalDateTime dateTime1 = LocalDateTime.now();
LocalDateTime dateTime2 = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
long seconds = ChronoUnit.SECONDS.between(dateTime1, dateTime2);
long minutes = ChronoUnit.MINUTES.between(dateTime1, dateTime2);
long hours = ChronoUnit.HOURS.between(dateTime1, dateTime2);
long days = ChronoUnit.DAYS.between(dateTime1, dateTime2);
System.out.println("时间差(秒):" + seconds);
System.out.println("时间差(分钟):" + minutes);
System.out.println("时间差(小时):" + hours);
System.out.println("时间差(天):" + days);
```
阅读全文