本文實例講述了JS實現獲取當前所在周的周六、周日。分享給大家供大家參考,具體如下:
需求:無論當前是哪一天,獲取當天所在周的周末 是哪一天
實現步驟:
比如,今天周一,則周日距離今天還有(7-1)=6天,那么將今天的時間(毫秒數),加上六天后的時間(6*_dayLongTime 毫秒數),然后根據date函數,轉換為幾月幾日。
1、獲取當天的時間
let _nowTime=new Date().getTime();
2、獲取當天是星期幾
let _week=_date.getDay();
3、設置一天的時長
let _dayLongTime=24*60*60*1000;
4、獲取周六周日距離現在還有多少毫秒
let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime;let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime;
5、將毫秒數轉為date對象
_furtureSundayTimes = new Date(_furtureSundayTimes);_furtureSaturdayTimes = new Date(_furtureSaturdayTimes);
6、根據日期獲取幾月幾日
// staurdaylet _satYear = _furtureSaturdayTimes.getFullYear();let _satMonth = _furtureSaturdayTimes.getMonth() + 1;let _satDay = _furtureSaturdayTimes.getDate();//sundaylet _sunYear = _furtureSundayTimes.getFullYear();let _sunMonth = _furtureSundayTimes.getMonth() + 1;let _sunDay = _furtureSundayTimes.getDate();
7、格式化
_satMonth = _satMonth >= 10 ? _satMonth : '0' + _satMonth;_satDay = _satDay >= 10 ? _satDay : '0' + _satDay;_sunMonth = _sunMonth >= 10 ? _sunMonth : '0' + _sunMonth;_sunDay = _sunDay >= 10 ? _sunDay : '0' + _sunDay;_mealSunDay = _satYear+'-'+_satMonth+'-'+_satDay;_mealSaturDay = _sunYear+ '-'+_sunMonth+'-'+_sunDay;
8、注:之所以不僅獲取周六,然后周日則用周六加1,就行,因為很有可能改周末不在同一個月份,比如3.31周六,4.01周日,月份不相同
9、方法體
function getWeekDay() { let _date = new Date(); let _nowTime = _date.getTime(); let _week = _date.getDay(); let _dayLongTime = 24 * 60 * 60 * 1000; let _furtureSundayTimes = _nowTime + (7 - _week) * _dayLongTime; let _furtureSaturdayTimes = _nowTime + (6 - _week) * _dayLongTime; _furtureSundayTimes = new Date(_furtureSundayTimes); _furtureSaturdayTimes = new Date(_furtureSaturdayTimes); // staurday let _satYear = _furtureSaturdayTimes.getFullYear(); let _satMonth = _furtureSaturdayTimes.getMonth() + 1; let _satDay = _furtureSaturdayTimes.getDate(); //sunday let _sunYear = _furtureSundayTimes.getFullYear(); let _sunMonth = _furtureSundayTimes.getMonth() + 1; let _sunDay = _furtureSundayTimes.getDate(); _satMonth = _satMonth >= 10 ? _satMonth : '0' + _satMonth; _satDay = _satDay >= 10 ? _satDay : '0' + _satDay; _sunMonth = _sunMonth >= 10 ? _sunMonth : '0' + _sunMonth; _sunDay = _sunDay >= 10 ? _sunDay : '0' + _sunDay; _mealSunDay = _satYear+'-'+_satMonth+'-'+_satDay; _mealSaturDay = _sunYear+ '-'+_sunMonth+'-'+_sunDay; let _weekendDay = [{ saturDay: _mealSunDay }, { sunDay: _mealSaturDay }] return _weekendDay;}
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答