根据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 12:44:10 浏览: 93
可以使用Java中的SimpleDateFormat类将String类型的时间转换为Date对象,然后再对Date对象进行处理。
首先,我们先将时间段转换为【2020-11-20 00:00:00,2021-10-09 23:59:59】,即将结束时间改为当天的最后一秒:
```java
String startTime = "2020-11-20 09:09:09";
String endTime = "2021-10-09 10:10:10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
endCalendar.set(Calendar.HOUR_OF_DAY, 23);
endCalendar.set(Calendar.MINUTE, 59);
endCalendar.set(Calendar.SECOND, 59);
endDate = endCalendar.getTime();
String newEndTime = sdf.format(endDate);
System.out.println(newEndTime);
```
输出结果为:2021-10-09 23:59:59
接下来,我们可以使用一个循环,每次增加一天,输出该天的开始时间和结束时间:
```java
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
while (calendar.getTime().before(endDate)) {
Date startOfDay = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date endOfDay = calendar.getTime();
System.out.println(sdf.format(startOfDay) + " - " + sdf.format(endOfDay));
}
// 输出最后一天的开始时间和结束时间
Date startOfDay = calendar.getTime();
System.out.println(sdf.format(startOfDay) + " - " + newEndTime);
```
输出结果为:
```
2020-11-20 09:09:09 - 2020-11-21 00:00:00
2020-11-21 00:00:00 - 2020-11-22 00:00:00
2020-11-22 00:00:00 - 2020-11-23 00:00:00
...
2021-10-07 00:00:00 - 2021-10-08 00:00:00
2021-10-08 00:00:00 - 2021-10-09 00:00:00
2021-10-09 00:00:00 - 2021-10-09 23:59:59
```
阅读全文