Java根据两个日期格式字符串得到中间时间段集合
时间: 2023-07-26 13:33:07 浏览: 156
你可以使用Java的日期时间类库,如Java 8的`java.time`包,来实现根据两个日期格式字符串得到中间时间段集合的功能。具体实现步骤如下:
1. 将两个日期格式字符串解析成`LocalDate`对象,例如:
```
String date1 = "2021-01-01";
String date2 = "2021-01-10";
LocalDate start = LocalDate.parse(date1);
LocalDate end = LocalDate.parse(date2);
```
2. 使用`java.time.temporal.ChronoUnit`类的`between`方法计算两个日期之间的天数,例如:
```
long daysBetween = ChronoUnit.DAYS.between(start, end);
```
3. 循环遍历天数,计算每一天的日期,并将其加入到结果集合中,例如:
```
List<LocalDate> dates = new ArrayList<>();
for (int i = 0; i <= daysBetween; i++) {
LocalDate date = start.plusDays(i);
dates.add(date);
}
```
4. 将结果集合中的日期转换成需要的格式字符串,例如:
```
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
List<String> dateStrings = dates.stream().map(formatter::format).collect(Collectors.toList());
```
完整代码示例:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DateUtils {
public static List<String> getDateRange(String date1, String date2) {
LocalDate start = LocalDate.parse(date1);
LocalDate end = LocalDate.parse(date2);
long daysBetween = ChronoUnit.DAYS.between(start, end);
List<LocalDate> dates = new ArrayList<>();
for (int i = 0; i <= daysBetween; i++) {
LocalDate date = start.plusDays(i);
dates.add(date);
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
List<String> dateStrings = dates.stream().map(formatter::format).collect(Collectors.toList());
return dateStrings;
}
public static void main(String[] args) {
List<String> dateRange = getDateRange("2021-01-01", "2021-01-10");
System.out.println(dateRange);
}
}
```
阅读全文