Java获取指定日期段每一天的开始时间和结束时间
Java获取指定日期24小时段开始时间和结束时间
// localDateTime转Date示例
Date start = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 时间区间工具类
*/
public class DateRangeUtils {
/**
* @description: 获取指定日期区间
* @author: H
* @param: [startDate, endDate]
**/
public static List<TimeRange> getDateRanges(Date startDate, Date endDate) {
List<TimeRange> dateRanges = new ArrayList<>();
LocalDateTime startDateTime = LocalDateTime.ofInstant(startDate.toInstant(), java.time.ZoneId.systemDefault());
LocalDateTime endDateTime = LocalDateTime.ofInstant(endDate.toInstant(), java.time.ZoneId.systemDefault());
while (!startDateTime.isAfter(endDateTime)) {
LocalDateTime startOfDay = startDateTime.with(LocalTime.MIN);
LocalDateTime endOfDay = startDateTime.with(LocalTime.MAX);
dateRanges.add(new TimeRange(startOfDay, endOfDay));
startDateTime = startDateTime.plusDays(1);
}
return dateRanges;
}
/**
* @description: 获取24小时区间
* @author: H
* @param: [date]
**/
public static List<TimeRange> get24HourTimeRanges(Date date) {
List<TimeRange> timeRanges = new ArrayList<>();
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), java.time.ZoneId.systemDefault());
for (int i = 0; i < 24; i++) {
int hour = i % 24; // 使用模运算确保小时数在0到23之间
LocalDateTime startTime = localDateTime.withHour(hour).withMinute(0).withSecond(0).withNano(0);
LocalDateTime endTime = localDateTime.withHour(hour).withMinute(59).withSecond(59).withNano(999999999);
timeRanges.add(new TimeRange(startTime, endTime));
}
return timeRanges;
}
public static class TimeRange {
private LocalDateTime startTime;
private LocalDateTime endTime;
public TimeRange(LocalDateTime startTime, LocalDateTime endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
public LocalDateTime getStartTime() {
return startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return startTime.format(formatter) + " - " + endTime.format(formatter);
}
}
public static void main(String[] args) {
Date startDate = Date.from(LocalDateTime.parse("2024-01-01T00:00:00").atZone(java.time.ZoneId.systemDefault()).toInstant());
Date endDate = Date.from(LocalDateTime.parse("2024-01-07T23:59:59").atZone(java.time.ZoneId.systemDefault()).toInstant());
List<TimeRange> dateRanges = getDateRanges(startDate, endDate);
System.out.println("七日区间:" + dateRanges);
List<TimeRange> hourTimeRanges = get24HourTimeRanges(startDate);
System.out.println("24小时区间" + hourTimeRanges);
}
}