java输出开始时间和结束时间中的所有年份
时间: 2023-08-30 13:07:20 浏览: 75
要输出开始时间和结束时间中的所有年份,你可以使用Java中的日期和时间类库来实现。以下是一个示例代码:
```java
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.ChronoUnit;
public class YearPrinter {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2025, 12, 31);
YearMonth startYearMonth = YearMonth.from(startDate);
YearMonth endYearMonth = YearMonth.from(endDate);
while (!startYearMonth.isAfter(endYearMonth)) {
System.out.println(startYearMonth.getYear());
startYearMonth = startYearMonth.plus(1, ChronoUnit.YEARS);
}
}
}
```
在这个示例中,我们使用`LocalDate`类表示开始时间和结束时间。然后,我们使用`YearMonth`类从开始时间和结束时间中提取年份和月份。接下来,我们使用一个循环来逐年输出开始时间和结束时间之间的所有年份。
你可以根据实际情况修改`startDate`和`endDate`的值来进行测试。运行上面的代码,它将输出开始时间和结束时间之间的所有年份。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)