JavaScript 得到上週時間範圍,本月時間範圍
阿新 • • 發佈:2019-02-08
//1. 得到本月一號為開始時間,得到當前時間減兩天為結束時間 function SetDayDate() { //當前時間減兩天 var dataValue = new Date(new Date().getTime() - (1000 * 60 * 60 * 48)); //(1000*60*60*24)是1千毫秒(是1秒)乘60(是1分)乘60(是1小時)*24(是一天)加減一天把前邊的-+換一下就行。 var year = dataValue.getFullYear(); var month = dataValue.getMonth() + 1; var day = dataValue.getDate(); if (month < 10) { month = '0' + month; } if (day < 10) { if (day < 1) { day = '01'; } else { day = '0' + day; } } var stime = year + '/' + month + '/' + '01'; //開始時間 var etime = year + '/' + month + '/' + day; //結束時間 } //2. 得到當前時間的上週時間範圍 function SetWeekDate() { var dataValue = new Date(); var year = dataValue.getFullYear(); var month = dataValue.getMonth() + 1; var day = dataValue.getDate(); var thisWeekStart; //本週週一的時間 if (dataValue.getDay() == 0) { //周天的情況; thisWeekStart = (new Date(year + '/' + month + '/' + day)).getTime() - ((dataValue.getDay()) + 6) * 86400000; } else { thisWeekStart = (new Date(year + '/' + month + '/' + day)).getTime() - ((dataValue.getDay()) - 1) * 86400000; } //獲得上週時間 var prevWeekStart = thisWeekStart - 7 * 86400000;//上週週一的時間 var prevWeekEnd = thisWeekStart - 1 * 86400000;//上週週日的時間 var stime = formatDate(new Date(prevWeekStart)); //開始時間 var etime = formatDate(new Date(prevWeekEnd)); //結束時間 } //3. 得到當前時間的上月時間範圍 function SetMonthDate() { var dataValue = new Date(); var currentYear = dataValue.getFullYear(); var currentMonth = dataValue.getMonth(); var prevCurrentYear = 0, prevCurrentMonth = 0; if (currentMonth == 0) { prevCurrentYear = currentYear - 1; prevCurrentMonth = 12; } else { prevCurrentYear = currentYear; prevCurrentMonth = currentMonth - 1; } var prevmonthLastday = (new Date(currentYear, currentMonth, 1)).getTime() - 86400000; var stime = formatDate(new Date(prevCurrentYear, prevCurrentMonth, 1)); //開始時間 var etime = formatDate(new Date(prevmonthLastday)); //結束時間 } //格式化日期:yyyy/MM/dd function formatDate(date) { var myyear = date.getFullYear(); var mymonth = date.getMonth() + 1; var myweekday = date.getDate(); if (mymonth < 10) { mymonth = "0" + mymonth; } if (myweekday < 10) { myweekday = "0" + myweekday; } return (myyear + "/" + mymonth + "/" + myweekday); }