假设我有startDate
,endDate
,currentDate
1.
我想忽略startDate
和endDate
超出currentDate
月的情况。
2.
当startDate
和currentDate
处于同一月份,但endDate
的月份大于currentDate
时,则在{{1 }}到startDate
一个月的结束日期。
startDate
当3.
与endDate
处于同一月份并且currentDate
小于startDate
个月时,则在{{1}之间创建一个列表}和currentDate
我想要一些处理此问题的方法的帮助。
谢谢
答案 0 :(得分:0)
首先让我们创建一个方法,该方法根据给定的开始日期和结束日期创建日期序列。此方法利用plusDays
中的LocalDate
在while循环中生成日期。
public static List<LocalDate> makeDateInterval(LocalDate startDate, LocalDate endDate) {
List<LocalDate> list = new ArrayList<>();
if (startDate.isAfter(endDate)) {
return list;
}
LocalDate nextDate = startDate;
while (nextDate.isBefore(endDate)) {
list.add(nextDate);
nextDate = nextDate.plusDays(1);
}
list.add(endDate);
return list;
}
要弄清开始和结束日期是什么,我们需要一个简单的逻辑来比较给定日期的月份,如果我们有一个有效的间隔,我们可以调用上述方法
public static List<LocalDate> buildDateRange(LocalDate startDate, LocalDate endDate, LocalDate currentDate) {
LocalDate firstDate = null;
LocalDate secondDate = null;
if (startDate.getMonth() == currentDate.getMonth()) {
firstDate = startDate;
secondDate = currentDate;
}
if (endDate.getMonth() == currentDate.getMonth()) {
secondDate = endDate;
if (firstDate == null) {
firstDate = currentDate;
}
}
if (firstDate == null || secondDate == null) {
return new ArrayList<>(); //No valid interval, return empty list
}
return makeDateInterval(firstDate, secondDate);
}
今天2月1日进行的简单测试
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate start = now.minusDays(5);
LocalDate end = now.plusDays(5);
System.out.println("Now: " + now + ", start: " + start + ", end: " +end);
List<LocalDate> list = buildDateRange(start, end, now);
for (LocalDate d : list) {
System.out.println(d);
}
}
生成以下输出
现在:2019-02-01,开始:2019-01-27,结束:2019-02-06
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06