js根據(jù)給定日期獲取月份的第幾周

參考網(wǎng)上很多方法修復(fù)了一些bug,例如有些方法當(dāng)日期為2019-09-01或者2019-04-01這種特殊日期時(shí)不能得到正確的結(jié)果,話不多說(shuō),直接上代碼:

function getWeekByDate(str){

str = Date.parse(str);

let date = new Date(str);

? ? let month = date.getMonth() + 1;

????let year = date.getFullYear();

? ? let dateN=new Date(str);

//月份第一天

? ? dateN=new Date(dateN.setDate(1));

? ? let w1=dateN.getDay();

? ? // 將字符串轉(zhuǎn)為標(biāo)準(zhǔn)時(shí)間格式

? ? let w = date.getDay();//周幾

? ? if(w===0&&w1!=0){//當(dāng)月第一天不是周天,當(dāng)前日期是周天

? ? w=7;

? ? }

? ? let week = Math.ceil((date.getDate() + 6 - w) / 7);

? ? if(w1!=1)//當(dāng)月第一天不是周一

? ? week = Math.ceil((date.getDate() + 6 - w) / 7) - 1;

? ? var cNum = ["零","一","二","三","四","五","六","七","八","九"];

? ? if (week === 0) {//第0周歸于上月的最后一周

? ? ? ? month = date.getMonth();

????if(month===0){//跨年

? ? ? ? month=12;

? ? ? ? year=year-1;

? ? ? ? }

? ? ? ? let dateLast = new Date(date);

? ? ? ? let dayLast = new Date(year, month, 0).getDate();

? ? ? ? let timestamp = new Date(year, month - 1, dayLast);

? ? ? ? w = new Date(timestamp).getDay();//周幾

? ? ? ? if (w === 0) {

? ? ? ? ? ? w = 7;

? ? ? ? }

? ? ? ? week = Math.ceil((timestamp.getDate() + 6 - w) / 7) - 1;

? ? }

? ? week=cNum[week];

? ? let time = year+"年"+month + "月第" + week + "周";

console.log(time);

}

參考博文:js獲取當(dāng)前日期是本月第幾周,月初如果不足一周歸于上月最后一周 - 簡(jiǎn)書

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容