console.log(getWeek('2018-02-01 06:00:00', '2018-02-03 18:00:00', 8, 20));
/**
* 获取日期段内某点到某点的日期时间
* @param begin:开始时间 eg:2018-02-09 10:00:00
* @param end:结束时间 eg:2018-02-19 18:00:00
* @param beginHour: 开始点数 eg:8
* @param endHour: 结束点数 eg:20
*/
function getWeek (begin, end, beginHour, endHour) {
var dateArr = new Array();
var stimeArr = begin.substring(0, 10).split("-");//=>["2018", "01", "01"]
var etimeArr = end.substring(0, 10).split("-");//=>["2018", "01", "30"]
var resultDate = [];
var stoday = new Date();
stoday.setUTCFullYear(stimeArr[0], stimeArr[1]-1, stimeArr[2]);
var etoday = new Date();
etoday.setUTCFullYear(etimeArr[0], etimeArr[1]-1, etimeArr[2]);
var unixDb = stoday.getTime();//开始时间的毫秒数
var unixDe = etoday.getTime();//结束时间的毫秒数
//先获取这个日期期间有哪些日期
for (var k = unixDb; k <= unixDe;) {
let needJudgeDate = msToDate(parseInt(k)).withoutTime;
dateArr.push(needJudgeDate);
k = k + 24*60*60*1000;
}
beginHour = beginHour < 10 ? '0'+beginHour : beginHour;
endHour = endHour < 10 ? '0'+endHour : endHour;
//再获取这些日期几点到几点的日期
for (let j in dateArr) {
let startDateTime = dateArr[j] + ' ' + beginHour + ':00:00';
let endDateTime = dateArr[j] + ' ' + endHour + ':00:00';
resultDate.push(startDateTime);
resultDate.push(endDateTime);
}
//传入的开始时间与resultDate第一个数据对比,谁大要谁
if (new Date(resultDate[0]).getTime() < new Date(begin).getTime() ) {
resultDate[0] = begin;
}
//传入的结束时间与resultDate最后一个数据对比,谁小要谁
if (new Date(resultDate[resultDate.length-1]).getTime() > new Date(end).getTime() ) {
resultDate[resultDate.length-1] = end;
}
return resultDate;
}
//根据毫秒数获取日期
function msToDate (msec) {
let datetime = new Date(msec);
let year = datetime.getFullYear();
let month = datetime.getMonth();
let date = datetime.getDate();
let hour = datetime.getHours();
let minute = datetime.getMinutes();
let second = datetime.getSeconds();
let result1 = year +
'-' +
((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
'-' +
((date + 1) < 10 ? '0' + date : date) +
' ' +
((hour + 1) < 10 ? '0' + hour : hour) +
':' +
((minute + 1) < 10 ? '0' + minute : minute) +
':' +
((second + 1) < 10 ? '0' + second : second);
let result2 = year +
'-' +
((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
'-' +
((date + 1) < 11 ? '0' + date : date);
let result = {
hasTime: result1,
withoutTime: result2
};
return result;
}
【JavaScript】获取日期段内几点到几点的日期时间
最新推荐文章于 2022-08-31 11:27:58 发布