java 获取两个日期之间的所有日期字符串
时间: 2023-08-29 12:07:26 浏览: 113
可以使用Java 8中的日期时间 API,使用`LocalDate`类和`ChronoUnit`枚举类来获取两个日期之间的所有日期字符串。下面是一个示例代码:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class DateUtils {
public static List<String> getDatesBetween(String startDate, String endDate, String pattern) {
List<String> dates = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDate start = LocalDate.parse(startDate, formatter);
LocalDate end = LocalDate.parse(endDate, formatter);
long days = ChronoUnit.DAYS.between(start, end);
for (int i = 0; i <= days; i++) {
LocalDate date = start.plusDays(i);
dates.add(date.format(formatter));
}
return dates;
}
}
```
使用方法:
```java
List<String> dates = DateUtils.getDatesBetween("2022-01-01", "2022-01-10", "yyyy-MM-dd");
for (String date : dates) {
System.out.println(date);
}
```
输出结果:
```
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
```
阅读全文