根据Date类型的时间段【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 14:44:00 浏览: 106
可以通过Java中的日期时间类来实现。具体步骤如下:
1. 将Date类型的时间段转换为LocalDateTime类型,并将时间段的开始时间和结束时间分别设置为当天的0时0分0秒和23时59分59秒。
```
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-11-20 09:09:09");
Date endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-10-09 10:10:10");
LocalDateTime startDateTime = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault()).with(LocalTime.MIN);
LocalDateTime endDateTime = LocalDateTime.ofInstant(endTime.toInstant(), ZoneId.systemDefault()).with(LocalTime.MAX);
```
2. 循环遍历时间段内的每一天,并获取每一天的开始时间和结束时间。
```
LocalDateTime currentDateTime = startDateTime;
while (!currentDateTime.isAfter(endDateTime)) {
LocalDateTime dayStartDateTime = currentDateTime.with(LocalTime.MIN);
LocalDateTime dayEndDateTime = currentDateTime.with(LocalTime.MAX);
System.out.println("Day " + currentDateTime.toLocalDate() + " start time: " + dayStartDateTime);
System.out.println("Day " + currentDateTime.toLocalDate() + " end time: " + dayEndDateTime);
currentDateTime = currentDateTime.plusDays(1);
}
```
完整代码如下:
```
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static void main(String[] args) throws Exception {
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-11-20 09:09:09");
Date endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-10-09 10:10:10");
LocalDateTime startDateTime = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault()).with(LocalTime.MIN);
LocalDateTime endDateTime = LocalDateTime.ofInstant(endTime.toInstant(), ZoneId.systemDefault()).with(LocalTime.MAX);
LocalDateTime currentDateTime = startDateTime;
while (!currentDateTime.isAfter(endDateTime)) {
LocalDateTime dayStartDateTime = currentDateTime.with(LocalTime.MIN);
LocalDateTime dayEndDateTime = currentDateTime.with(LocalTime.MAX);
System.out.println("Day " + currentDateTime.toLocalDate() + " start time: " + dayStartDateTime);
System.out.println("Day " + currentDateTime.toLocalDate() + " end time: " + dayEndDateTime);
currentDateTime = currentDateTime.plusDays(1);
}
}
}
```
阅读全文