使用java提供一个方法:根据日期条件,往前推1天,向后推7天,返回一个集合
时间: 2023-11-27 10:49:51 浏览: 70
可以使用Java 8的时间API LocalDateTime和Stream API来实现该方法。具体代码实现如下:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class DateUtils {
public static List<String> getDates(String startDateStr, String endDateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(startDateStr, formatter);
LocalDate endDate = LocalDate.parse(endDateStr, formatter);
List<String> dates = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dates.add(startDate.format(formatter));
startDate = startDate.plusDays(1);
}
return dates;
}
public static List<String> getDatesOneDayBeforeAndSevenDaysAfter(String dateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(dateStr, formatter);
LocalDate startDate = date.minusDays(1);
LocalDate endDate = date.plusDays(7);
return getDates(startDate.format(formatter), endDate.format(formatter));
}
public static void main(String[] args) {
String dateStr = "2022-01-01";
List<String> dates = getDatesOneDayBeforeAndSevenDaysAfter(dateStr);
System.out.println(dates);
}
}
```
该方法中,`getDates`方法用于获取两个日期之间的日期集合,`getDatesOneDayBeforeAndSevenDaysAfter`方法则是根据传入的日期字符串,获取该日期前一天到后七天的日期集合。最后在`main`方法中调用`getDatesOneDayBeforeAndSevenDaysAfter`方法,并将返回的日期集合打印出来。
阅读全文