js獲取選中日期的當周的周一和周日 ...
js獲取選中日期的當周的周一和周日
1 console.log(getNowDateAndNowWeek(1539187200000)); 2 3 /** 4 * 獲取當月的第幾周 5 * a = d = 當前日期 6 * b = 6 - w = 當前周的還有幾天過完(不算今天) 7 * a + b 的和在除以7 就是當天是當前月份的第幾周 8 */ 9 function getMonthWeek(a, b, c) { 10 11 var date = new Date(a, parseInt(b) - 1, c), w = date.getDay(), d = date.getDate(); 12 return Math.ceil( 13 (d + 6 - w) / 7 14 ); 15 }; 16 17 18 /** 19 * 獲取選擇當前的第幾周,當前的周一、周日 20 * time 選擇日期的時間戳 21 */ 22 function getNowDateAndNowWeek(time) { 23 //選中的時間戳 24 var timestamp = time; 25 var serverDate = new Date(time); 26 27 //本周周日的的時間 28 var sundayTiem = timestamp + ((7 - serverDate.getDay()) * 24 * 60 * 60 * 1000) 29 var SundayData = new Date(sundayTiem); 30 //年 31 var tomorrowY = SundayData.getFullYear(); 32 //月 33 var tomorrowM = (SundayData.getMonth() + 1 < 10 ? '0' + (SundayData.getMonth() + 1) : SundayData.getMonth() + 1); 34 //日 35 var tomorrowD = SundayData.getDate() < 10 ? '0' + SundayData.getDate() : SundayData.getDate(); 36 console.log('周日: ' + tomorrowY + '-' + tomorrowM + '-' + tomorrowD); 37 38 // 本周周一的時間 39 var mondayTime = timestamp - ((serverDate.getDay() - 1) * 24 * 60 * 60 * 1000) 40 var mondayData = new Date(mondayTime); 41 //年 42 var mondayY = mondayData.getFullYear(); 43 //月 44 var mondayM = (mondayData.getMonth() + 1 < 10 ? '0' + (mondayData.getMonth() + 1) : mondayData.getMonth() + 1); 45 //日 46 var mondayD = mondayData.getDate() < 10 ? '0' + mondayData.getDate() : mondayData.getDate(); 47 var nowWeek = getMonthWeek(tomorrowY, tomorrowM, tomorrowD); 48 //輸出值 49 var config = { 50 SunDay: tomorrowY + '/' + tomorrowM + '/' + tomorrowD, 51 Monday: mondayY + '/' + mondayM + '/' + mondayD, 52 nowWeek: nowWeek 53 } 54 return config; 55 }