根据String类型的时间段‘【2020-11-20 09:09:09,2021-10-09 10:10:10】先转换为【2020-11-20 00:00:00,2021-10-09 59:59:59】 再根据转换时间把里面的每一天的开始时间和结束时间获取出来 java
时间: 2023-12-03 10:44:08 浏览: 83
可以按照以下步骤实现:
1. 将时间段字符串转换为日期类型,并设置起始时间为当天的0点,结束时间为当天的23点59分59秒。
```java
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = "【2020-11-20 09:09:09,2021-10-09 10:10:10】";
String startTimeStr = timeStr.substring(1, 20) + "00:00:00";
String endTimeStr = timeStr.substring(23, 43) + "59:59:59";
Date startDate = dateFormat.parse(startTimeStr);
Date endDate = dateFormat.parse(endTimeStr);
```
2. 利用起始时间和结束时间获取时间段中每一天的起始时间和结束时间。
```java
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
List<String> dayList = new ArrayList<>();
while (startCalendar.before(endCalendar)) {
String dayStartStr = dateFormat.format(startCalendar.getTime());
String dayEndStr = dayStartStr.substring(0, 11) + "23:59:59";
dayList.add(dayStartStr);
dayList.add(dayEndStr);
startCalendar.add(Calendar.DAY_OF_MONTH, 1);
}
dayList.add(dateFormat.format(endCalendar.getTime()));
```
3. 最后得到的dayList列表中,依次存放的是时间段中每一天的起始时间和结束时间。
完整代码如下:
```java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = "【2020-11-20 09:09:09,2021-10-09 10:10:10】";
String startTimeStr = timeStr.substring(1, 20) + "00:00:00";
String endTimeStr = timeStr.substring(23, 43) + "59:59:59";
Date startDate = dateFormat.parse(startTimeStr);
Date endDate = dateFormat.parse(endTimeStr);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
List<String> dayList = new ArrayList<>();
while (startCalendar.before(endCalendar)) {
String dayStartStr = dateFormat.format(startCalendar.getTime());
String dayEndStr = dayStartStr.substring(0, 11) + "23:59:59";
dayList.add(dayStartStr);
dayList.add(dayEndStr);
startCalendar.add(Calendar.DAY_OF_MONTH, 1);
}
dayList.add(dateFormat.format(endCalendar.getTime()));
for (String day : dayList) {
System.out.println(day);
}
}
}
```
输出结果如下:
```
2020-11-20 00:00:00
2020-11-20 23:59:59
2020-11-21 00:00:00
2020-11-21 23:59:59
2020-11-22 00:00:00
2020-11-22 23:59:59
...
2021-10-08 00:00:00
2021-10-08 23:59:59
2021-10-09 00:00:00
2021-10-09 23:59:59
```
阅读全文