用Duration类计算出现在离十一还有XX天XX小时XX分钟。 用Peroid计算出现在明年十一还有XX年XX月XX日。
时间: 2024-05-10 15:16:53 浏览: 5
以下是用Java实现的代码:
```java
import java.time.*;
import java.time.temporal.ChronoUnit;
public class Countdown {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate eleven = LocalDate.of(now.getYear(), 11, 11);
Period period = Period.between(now, eleven);
System.out.printf("距离十一还有%d天%d小时%d分钟\n",
period.getDays(), LocalDateTime.now().until(LocalDateTime.of(now.getYear(), 11, 11, 0, 0), ChronoUnit.HOURS),
LocalDateTime.now().until(LocalDateTime.of(now.getYear(), 11, 11, 0, 0), ChronoUnit.MINUTES) % 60);
LocalDate nextEleven = now.withMonth(11).withDayOfMonth(11);
if (nextEleven.isBefore(now)) {
nextEleven = nextEleven.plusYears(1);
}
Period nextPeriod = Period.between(now, nextEleven);
System.out.printf("距离明年十一还有%d年%d月%d天\n", nextPeriod.getYears(), nextPeriod.getMonths(), nextPeriod.getDays());
}
}
```
代码中,我们使用 `LocalDate` 类来表示日期,使用 `LocalDateTime` 类来表示日期和时间。我们首先获取当前日期 `now`,然后创建一个 `LocalDate` 对象 `eleven` 表示每年的十一月十一日。我们使用 `Period` 类来计算当前时间和 `eleven` 之间的差距,即距离十一还有多少天、多少小时、多少分钟。
对于距离明年十一的计算,我们先创建一个 `LocalDate` 对象 `nextEleven`,表示下一个十一月十一日,如果当前日期已经过了这个日期,我们就将 `nextEleven` 加上一年。然后我们再次使用 `Period` 类来计算当前时间和 `nextEleven` 之间的差距,即距离明年十一还有多少年、多少月、多少天。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)