java根据开始日期结束日期字符串生成中间每天日期集合,加效果
时间: 2024-03-10 11:43:42 浏览: 69
您好,根据您的要求,我可以为您提供以下Java代码示例:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class DateUtils {
// 将日期字符串转换为LocalDate对象
private static LocalDate parseDate(String dateStr, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return LocalDate.parse(dateStr, formatter);
}
// 将LocalDate对象转换为日期字符串
private static String formatDate(LocalDate date, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return date.format(formatter);
}
// 获取两个日期之间的所有日期
public static List<String> getDatesBetween(String startDateStr, String endDateStr, String pattern) {
List<String> dateList = new ArrayList<>();
LocalDate startDate = parseDate(startDateStr, pattern);
LocalDate endDate = parseDate(endDateStr, pattern);
while (!startDate.isAfter(endDate)) {
dateList.add(formatDate(startDate, pattern));
startDate = startDate.plusDays(1);
}
return dateList;
}
}
```
使用示例:
```java
public static void main(String[] args) {
String startDateStr = "2022-01-01";
String endDateStr = "2022-01-10";
String pattern = "yyyy-MM-dd";
List<String> dateList = DateUtils.getDatesBetween(startDateStr, endDateStr, pattern);
for (String dateStr : dateList) {
System.out.println(dateStr);
}
}
```
输出结果:
```
2022-01-01
2022-01-02
2022-01-03
2022-01-04
2022-01-05
2022-01-06
2022-01-07
2022-01-08
2022-01-09
2022-01-10
```
希望能够帮助到您!
阅读全文