java根据起止时间按天拆分日期
时间: 2023-05-23 15:06:38 浏览: 389
java实现日期拆分的方法
A:
实现这个功能可以使用Java标准库中的LocalDate类。具体实现步骤如下:
1. 定义起止时间和日期格式
```
String startDateStr = "2021-01-01";
String endDateStr = "2021-01-15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
```
2. 转换起止时间为LocalDate类型
```
LocalDate startDate = LocalDate.parse(startDateStr, formatter);
LocalDate endDate = LocalDate.parse(endDateStr, formatter);
```
3. 循环遍历日期范围,按天拆分日期
```
List<LocalDate> dateList = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dateList.add(startDate);
startDate = startDate.plusDays(1);
}
```
4. 输出拆分后的日期列表
```
for (LocalDate date : dateList) {
System.out.println(date.format(formatter));
}
```
完整代码示例:
```
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class SplitDateByDay {
public static void main(String[] args) {
String startDateStr = "2021-01-01";
String endDateStr = "2021-01-15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(startDateStr, formatter);
LocalDate endDate = LocalDate.parse(endDateStr, formatter);
List<LocalDate> dateList = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dateList.add(startDate);
startDate = startDate.plusDays(1);
}
for (LocalDate date : dateList) {
System.out.println(date.format(formatter));
}
}
}
```
阅读全文