用LocalDateTime类型计算
时间: 2024-05-17 19:10:24 浏览: 90
LocalDateTime是Java 8中提供的时间日期API之一,它可以处理日期和时间,不包含时区信息。以下是使用LocalDateTime类型计算的示例:
1. 计算两个时间之间的时间差
```
LocalDateTime startTime = LocalDateTime.of(2021, 10, 1, 10, 0, 0);
LocalDateTime endTime = LocalDateTime.of(2021, 10, 1, 12, 0, 0);
Duration duration = Duration.between(startTime, endTime);
System.out.println("时间差:" + duration.toMinutes() + "分钟");
```
2. 在当前时间上增加指定的时间
```
LocalDateTime now = LocalDateTime.now();
LocalDateTime newTime = now.plusHours(2).plusMinutes(30);
System.out.println("当前时间:" + now);
System.out.println("增加2小时30分钟后的时间:" + newTime);
```
3. 计算两个日期之间的天数差
```
LocalDate startDate = LocalDate.of(2021, 10, 1);
LocalDate endDate = LocalDate.of(2021, 10, 10);
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("日期差:" + daysBetween + "天");
```
4. 计算两个日期之间的月份差
```
YearMonth startMonth = YearMonth.of(2021, 10);
YearMonth endMonth = YearMonth.of(2022, 3);
long monthsBetween = ChronoUnit.MONTHS.between(startMonth, endMonth);
System.out.println("月份差:" + monthsBetween + "个月");
```
阅读全文