package com.yyc.utils;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
/**
* @Auther: yangyongcui
* @Date: 2019/9/18: 17:26
* @Description:
*/
public class DateUtils {
/**
* 跨天计算 两个时间之间,去除指定时间段,剩余时间的和 看一共有多少有效的时间 返回了 秒数
*
* @param start 开始时间 格式2019-09-17T09:09:55
* @param end 结束时间2019-09-18T09:09:55
* @param range 不需要计算小时数的 时间段 "20:00:00-08:00:00"
*/
public String getInterval(String start, String end, String range) {
//获取要查询的日期范围内间隔了几天
long days = getDays(start, end);
if (days == 0) {//查询是当天的日期,也就是开始和结束都是属于同一天,不计算直接返回null 范围必须有一天的间隔
return null;
} else if (days >= 1) {
//无效时间
String[] splitForNo = range.split("-");
LocalTime startTimeForNo = LocalTime.parse(splitForNo[0]);
LocalTime endTimeForNo = LocalTime.parse(splitForNo[1]);
//要查询的时间范围
LocalTime startTime = LocalTime.parse(start.split("T")[1]);
LocalTime endTime = LocalTime.parse(end.split("T")[1]);
long startSeconds = Duration.between(startTime, startTimeForNo).toMillis() / 1000;
long endSeconds = Duration.between(endTimeForNo, endTime).toMillis() / 1000;
if (startSeconds < 0) {//说明 开始时间在无效时间之内
startSeconds = 0;
}
if (endSeconds < 0) {//说明 结束时间在无效时间之内
endSeconds = 0;
}
long noneSecones = getNoneSecones(startTimeForNo,endTimeForNo);
long l = startSeconds + endSeconds + (3600*24 - noneSecones) * (days - 1);
return String.valueOf(l);
}
return null;
}
/**
* 获取指定范围内的间隔秒数
*
* @return
*/
private long getNoneSecones( LocalTime startTimeForNo, LocalTime endTimeForNo) {
//凌晨时间
LocalTime zeroTime = LocalTime.parse("23:59:59");//0-23
//计算开始时间到凌晨12点的秒数
long betweenStart = Duration.between(startTimeForNo, zeroTime).abs().toMillis() / 1000 + 1;//补上面的那一秒24:00:00
//计算结束时间到凌晨12点的秒数
zeroTime = LocalTime.parse("00:00:00");
long betweenEnd = Duration.between(zeroTime, endTimeForNo).abs().toMillis() / 1000;
//无效时间总和是
return betweenStart + betweenEnd;
}
/**
* 算出指定时间的间隔天数
*
* @param start
* @param end
* @return
*/
private long getDays(String start, String end) {
String t = start.split("T")[0] + "T00:00:00";
String t2 = end.split("T")[0] + "T00:00:00";
LocalDateTime startT = LocalDateTime.parse(t);
LocalDateTime endT = LocalDateTime.parse(t2);
//获取参数间隔的天数
return Duration.between(startT, endT).toDays();
}
}
给定一个日期范围,再给定一个时间段,求当前日期范围内,除了该时间段的有效时间
最新推荐文章于 2022-07-11 22:24:57 发布