用java 给出形如"2023-05-11 00:00:00" 的字符串之间的每一天,要求以Date对象传出
时间: 2024-02-22 19:58:01 浏览: 42
可以使用Java 8中的LocalDate类和Legacy Date-Time API(java.util.Date)来实现:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) {
String startStr = "2023-05-11 00:00:00";
String endStr = "2023-05-15 00:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDate startDate = LocalDate.parse(startStr, formatter);
LocalDate endDate = LocalDate.parse(endStr, formatter);
List<Date> dateList = new ArrayList<>();
LocalDate date = startDate;
while (!date.isAfter(endDate)) {
Date legacyDate = null;
try {
legacyDate = new SimpleDateFormat("yyyy-MM-dd").parse(date.toString());
} catch (ParseException e) {
e.printStackTrace();
}
dateList.add(legacyDate);
date = date.plusDays(1);
}
for (Date dateObj : dateList) {
System.out.println(dateObj);
}
}
}
```
这段代码将会输出从2023年5月11日到2023年5月15日之间的每一天,以Date对象的形式传出。