JavaScript关于操作时间段代码
Posted 当代英雄
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript关于操作时间段代码相关的知识,希望对你有一定的参考价值。
/* 获取时间段内属于星期一(*)的日期们 * begin: 开始时间 * end:结束时间 * weekNum:星期几 {number} */ function getWeek (begin, end, weekNum){ var dateArr = new Array(); var stimeArr = begin.split("-");//=>["2018", "01", "01"] var etimeArr = end.split("-");//=>["2018", "01", "30"] 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; //不加这个if判断直接push的话就是已知时间段内的所有日期 if (new Date(needJudgeDate).getDay() === weekNum) { dateArr.push(needJudgeDate); } k = k + 24*60*60*1000; } return dateArr; } //根据毫秒数获取日期 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; } function getDayByWeekDay(day) { if (day == ‘星期日‘) { return 0; } else if (day == ‘星期一‘) { return 1; } else if (day == ‘星期二‘) { return 2; } else if (day == ‘星期三‘) { return 3; } else if (day == ‘星期四‘) { return 4; } else if (day == ‘星期五‘) { return 5; } else if (day == ‘星期六‘) { return 6; } } /** * 获取两个日期之间所有的日期 * @param start * @param end * @returns {[]} */ function getBetweenDateStr(start,end){ var result = []; var beginDay = start.split("-"); var endDay = end.split("-"); var diffDay = new Date(); var dateList = new Array; var i = 0; diffDay.setDate(beginDay[2]); diffDay.setMonth(beginDay[1]-1); diffDay.setFullYear(beginDay[0]); result.push(start); while(i == 0){ var countDay = diffDay.getTime() + 24 * 60 * 60 * 1000; diffDay.setTime(countDay); dateList[2] = diffDay.getDate(); dateList[1] = diffDay.getMonth() + 1; dateList[0] = diffDay.getFullYear(); if(String(dateList[1]).length == 1){dateList[1] = "0"+dateList[1]}; if(String(dateList[2]).length == 1){dateList[2] = "0"+dateList[2]}; result.push(dateList[0]+"-"+dateList[1]+"-"+dateList[2]); if(dateList[0] == endDay[0] && dateList[1] == endDay[1] && dateList[2] == endDay[2]){ i = 1; } }; return result; }
以上是关于JavaScript关于操作时间段代码的主要内容,如果未能解决你的问题,请参考以下文章