java:以一年为单位划分时间段



我在java中有两个日期。一个日期是开始日期,第二个日期是结束日期。请参阅我的代码:

LocalDate startdate = LocalDate.parse("2022-12-01");
LocalDate finishdate = LocalDate.parse("2024-10-05");

我喜欢把这段时间分成单独的几年。例如

p1 = 2022-12-01 ... 2022-12-31
p2 = 2023-01-01 ... 2023-12-31
P3 = 2024-01-01 ... 2024-10-05

但是我怎么能在岁月中循环呢?检查一下?

一种简单的方法可能是使用TemporalAdjusters[1]当然,还有很多其他方法;(

假设我们创建以下值对象:

class Period{
final LocalDate begin;
final LocalDate end;
Period(LocalDate begin, LocalDate end) {
this.begin = begin;
this.end = end;
}
@Override
public String toString() {
return String.format("%s - %s", begin, end);
}
}

(在这种情况下是递归的(逻辑可能如下-从startdate、finishdate和空列表开始-只要finishdate在最后一个周期结束之后,就添加周期:

List<Period> periods(LocalDate startdate, LocalDate finishdate, List<Period> periodsList){
final LocalDate periodEnd = startdate.with(lastDayOfYear());
if(periodEnd.isBefore(finishdate)){
periodsList.add(new Period(startdate, periodEnd));
return periods(periodEnd.plusDays(1), finishdate, periodsList);
}
periodsList.add(new Period(finishdate.with(firstDayOfYear()), finishdate));
return periodsList;
}

一个带有简单main的完整工作示例可能如下所示:

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static java.time.temporal.TemporalAdjusters.firstDayOfYear;
import static java.time.temporal.TemporalAdjusters.lastDayOfYear;
public class Periods {
public static void main(String[] args) {
final LocalDate startdate = LocalDate.parse("2022-12-01");
final LocalDate finishdate = LocalDate.parse("2024-10-05");
periods(startdate, finishdate).forEach(System.out::println);
}
private static List<Period> periods(LocalDate startdate, LocalDate finishdate){
return periods(startdate, finishdate, new ArrayList<>());
}
private static List<Period> periods(LocalDate startdate, LocalDate finishdate, List<Period> periodsList){
final LocalDate periodEnd = startdate.with(lastDayOfYear());
if(periodEnd.isBefore(finishdate)){
periodsList.add(new Period(startdate, periodEnd));
return periods(periodEnd.plusDays(1), finishdate, periodsList);
}
periodsList.add(new Period(finishdate.with(firstDayOfYear()), finishdate));
return periodsList;
}
}
class Period{
final LocalDate begin;
final LocalDate end;
Period(LocalDate begin, LocalDate end) {
this.begin = begin;
this.end = end;
}
@Override
public String toString() {
return String.format("%s - %s", begin, end);
}
}

正如评论中所指出的,Java提供了一个Period[2]类,它也可以使用。为了简单起见——打印开始和结束——这里引入了一个简单的bean类。

最新更新