根据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:09 浏览: 77
可以通过以下步骤来实现:
1. 将时间段字符串转换为时间对象
2. 将起始时间的时分秒设置为 00:00:00,将结束时间的时分秒设置为 23:59:59
3. 循环遍历每一天,获取当天的开始时间和结束时间
下面是具体的Java代码实现:
```java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtil {
public static void main(String[] args) throws Exception {
String timeStr = "2020-11-20 09:09:09,2021-10-09 10:10:10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startTime = sdf.parse(timeStr.split(",")[0]);
Date endTime = sdf.parse(timeStr.split(",")[1]);
// 将起始时间的时分秒设置为 00:00:00,将结束时间的时分秒设置为 23:59:59
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
startTime = cal.getTime();
cal.setTime(endTime);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
endTime = cal.getTime();
List<String> dayList = new ArrayList<String>();
cal.setTime(startTime);
while (cal.getTime().before(endTime)) {
String dayStart = sdf.format(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.SECOND, -1);
String dayEnd = sdf.format(cal.getTime());
cal.add(Calendar.SECOND, 1);
dayList.add(dayStart + "," + dayEnd);
}
dayList.add(sdf.format(cal.getTime()) + "," + sdf.format(endTime));
// 输出每一天的开始时间和结束时间
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-07 00:00:00,2021-10-07 23:59:59
2021-10-08 00:00:00,2021-10-08 23:59:59
2021-10-09 00:00:00,2021-10-09 10:10:10
```
阅读全文