java中把给定的时间段按年分割
时间: 2024-02-01 18:13:25 浏览: 156
你可以使用Java 8中的DateTime API来实现这个功能。具体步骤如下:
1. 使用`LocalDate`类来表示起始时间和结束时间。
```
LocalDate start = LocalDate.of(2010, 1, 1);
LocalDate end = LocalDate.of(2020, 12, 31);
```
2. 计算起始时间和结束时间之间相差的年数。
```
long yearsBetween = ChronoUnit.YEARS.between(start, end);
```
3. 根据相差的年数,循环遍历每一年并输出。
```
for (int i = 0; i <= yearsBetween; i++) {
LocalDate yearStart = start.plusYears(i);
LocalDate yearEnd = yearStart.plusYears(1).minusDays(1);
System.out.println(yearStart.getYear() + ": " + yearStart + " - " + yearEnd);
}
```
完整代码如下:
```
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2010, 1, 1);
LocalDate end = LocalDate.of(2020, 12, 31);
long yearsBetween = ChronoUnit.YEARS.between(start, end);
for (int i = 0; i <= yearsBetween; i++) {
LocalDate yearStart = start.plusYears(i);
LocalDate yearEnd = yearStart.plusYears(1).minusDays(1);
System.out.println(yearStart.getYear() + ": " + yearStart + " - " + yearEnd);
}
}
}
```
输出结果为:
```
2010: 2010-01-01 - 2010-12-31
2011: 2011-01-01 - 2011-12-31
2012: 2012-01-01 - 2012-12-31
2013: 2013-01-01 - 2013-12-31
2014: 2014-01-01 - 2014-12-31
2015: 2015-01-01 - 2015-12-31
2016: 2016-01-01 - 2016-12-31
2017: 2017-01-01 - 2017-12-31
2018: 2018-01-01 - 2018-12-31
2019: 2019-01-01 - 2019-12-31
2020: 2020-01-01 - 2020-12-31
```
阅读全文