下面一段代碼給大家介紹JS獲取月的第幾周和年的第幾周,具體代碼如下所述:
var getMonthWeek = function (a, b, c) { /* a = d = 當(dāng)前日期 b = 6 - w = 當(dāng)前周的還有幾天過(guò)完(不算今天) a + b 的和在除以7 就是當(dāng)天是當(dāng)前月份的第幾周 */ var date = new Date(a, parseInt(b) - 1, c), w = date.getDay(), d = date.getDate(); return Math.ceil( (d + 6 - w) / 7 ); }; var getYearWeek = function (a, b, c) { /* date1是當(dāng)前日期 date2是當(dāng)年第一天 d是當(dāng)前日期是今年第多少天 用d + 當(dāng)前年的第一天的周差距的和在除以7就是本年第幾周 */ var date1 = new Date(a, parseInt(b) - 1, c), date2 = new Date(a, 0, 1), d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000); return Math.ceil( (d + ((date2.getDay() + 1) - 1)) / 7 ); }; //獲取時(shí)間的代碼就不寫了 console.log(getMonthWeek(2019,1,1));//返回1補(bǔ)充:js 獲取每月有幾周,當(dāng)前時(shí)間在當(dāng)月第幾周,今天周幾等方法
因產(chǎn)品需要展示相關(guān)時(shí)間,現(xiàn)總結(jié)如下方法:以供日后參考:
獲取每月有幾周
// year:年 month:月 day:日 getWeeks(year, month, day) { const d = new Date() // 該月第一天 d.setFullYear(2018, 6, 1) let w1 = d.getDay() if (w1 === 0) { w1 = 7 } // 該月天數(shù) d.setFullYear(2018, 7, 0) const dd = d.getDate() // 該月第一個(gè)周一 let d1 if (w1 !== 1) { d1 = 7 - w1 + 2 } else { d1 = 1 } const WEEK_NUB = Math.ceil((dd - d1 + 1) / 7) return WEEK_NUB }獲得周期名字
getWeekName() { const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] const index = new Date().getDay() const currDay = weekday[index] return currDay}獲得當(dāng)前日期在當(dāng)月第幾周
// a: 年 b: 月 c: 日 (不包括跟上個(gè)月重合的部分) getMonthWeek(a, b, c) { const date = new Date(a, parseInt(b) - 1, c) const w = date.getDay() const d = date.getDate() return Math.ceil( (d + 6 - w) / 7 ) }總結(jié)
以上所述是小編給大家介紹的JS獲取月的第幾周和年的第幾周實(shí)例代碼 ,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注