Java
截取时间段,以半个小时为单位
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 截取小时时间段,按指定时间间隔切割
*
* @param startTime 2022-04-09 06:00:00 格式强制 年月日时分秒 yyyy-MM-dd HH:mm:ss
* @param endTime 2022-04-09 06:00:00 格式强制 年月日时分秒 yyyy-MM-dd HH:mm:ss
* @param intervalMinutes 时间间隔(分钟),如30表示半小时,60表示一小时
* @return 分割后的时间段列表
*/
public static List<String> getTimeParts(String startTime, String endTime, int intervalMinutes) {
// 验证间隔参数
if (intervalMinutes <= 0 || 1440 % intervalMinutes != 0) {
throw new IllegalArgumentException("间隔分钟数必须是能整除1440(24小时)的正整数");
}
String day = startTime.split(" ")[0];
String startHm = startTime.split(" ")[1].substring(0, 5);
String endHm = endTime.split(" ")[1].substring(0, 5);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime start = LocalTime.parse(startHm, timeFormatter);
LocalTime end = LocalTime.parse(endHm, timeFormatter);
// 处理跨天的情况
if (end.isBefore(start) || end.equals(start)) {
end = end.plusHours(24);
}
List<String> timeSlots = new ArrayList<>();
LocalTime current = start;
while (current.isBefore(end)) {
timeSlots.add(day + " " + current.format(timeFormatter) + ":00");
current = current.plusMinutes(intervalMinutes);
}
// 添加结束时间点
if (!current.minusMinutes(intervalMinutes).equals(end)) {
timeSlots.add(day + " " + end.format(timeFormatter) + ":00");
}
return timeSlots;
}
//使用案例
// 半小时间隔
List<String> halfHourSlots = getTimeParts("2022-04-09 06:00:00", "2022-04-09 12:00:00", 30);
// 一小时间隔
List<String> hourSlots = getTimeParts("2022-04-09 06:00:00", "2022-04-09 12:00:00", 60);
// 15分钟间隔
List<String> quarterHourSlots = getTimeParts("2022-04-09 06:00:00", "2022-04-09 12:00:00", 15);
注意事项:
间隔分钟数必须是能整除1440(24小时)的正整数(如15, 30, 60, 120等)
如果结束时间小于开始时间,会自动当作第二天的时间处理
返回的列表包含开始时间点和结束时间点,以及中间的所有间隔时间点
获取当前时间前半个小时
/*获取当前时间前半个小时 现在13:35 返回 13:00 */
public static String startTime() {
Calendar calendar = Calendar.getInstance();
if (DateUtil.minute(DateUtil.date()) / 31 == 1) {
calendar.set(Calendar.MINUTE, 0);
} else {
calendar.add(Calendar.HOUR, -1);
calendar.set(Calendar.MINUTE, 30);
}
calendar.set(Calendar.SECOND, 0);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long nowTime = calendar.getTimeInMillis();
String timeNextTime = simpleDateFormat.format(nowTime);
System.out.println(timeNextTime);
return timeNextTime;//35
}
List<String> collect = dtos.stream().map(BizClassDto::getName).collect(Collectors.toList());
long count = collect.stream().distinct().count();
if (count < collect.size()) {
throw new ServiceException("班级名不能重复");
}
日夜颠倒头发少 ,单纯好骗恋爱脑 ,会背九九乘法表 ,下雨只会往家跑 ,搭讪只会说你好 ---- 2050781802@qq.com