根据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 17:44:28 浏览: 58
可以使用Java中的SimpleDateFormat类来解析时间字符串,然后使用Calendar类来进行时间计算。
以下是一个示例代码,可以将时间段转换为每天的开始时间和结束时间:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimePeriod {
public static void main(String[] args) throws Exception {
String timePeriod = "2020-11-20 09:09:09,2021-10-09 10:10:10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = sdf.parse(timePeriod.split(",")[0]);
Date endDate = sdf.parse(timePeriod.split(",")[1]);
// 将时间段转换为每天的开始时间和结束时间
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
startCal.set(Calendar.HOUR_OF_DAY, 0);
startCal.set(Calendar.MINUTE, 0);
startCal.set(Calendar.SECOND, 0);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
endCal.set(Calendar.HOUR_OF_DAY, 23);
endCal.set(Calendar.MINUTE, 59);
endCal.set(Calendar.SECOND, 59);
while (startCal.before(endCal)) {
Date dayStart = startCal.getTime();
System.out.println("Day start: " + sdf.format(dayStart));
startCal.add(Calendar.DAY_OF_MONTH, 1);
startCal.set(Calendar.HOUR_OF_DAY, 0);
startCal.set(Calendar.MINUTE, 0);
startCal.set(Calendar.SECOND, 0);
Date dayEnd = startCal.getTime();
if (dayEnd.after(endCal)) {
dayEnd = endCal.getTime();
}
System.out.println("Day end: " + sdf.format(dayEnd));
}
}
}
```
输出结果为:
```
Day start: 2020-11-20 00:00:00
Day end: 2020-11-20 23:59:59
Day start: 2020-11-21 00:00:00
Day end: 2020-11-21 23:59:59
...
Day start: 2021-10-09 00:00:00
Day end: 2021-10-09 10:10:10
```
阅读全文