下面一段代碼給大家介紹JS獲取月的第幾周和年的第幾周,具體代碼如下所述:
var getMonthWeek = function (a, b, c) { /* a = d = 當前日期 b = 6 - w = 當前周的還有幾天過完(不算今天) a + b 的和在除以7 就是當天是當前月份的第幾周 */ 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是當前日期 date2是當年第一天 d是當前日期是今年第多少天 用d + 當前年的第一天的周差距的和在除以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 ); }; //獲取時間的代碼就不寫了 console.log(getMonthWeek(2019,1,1));//返回1補充:js 獲取每月有幾周,當前時間在當月第幾周,今天周幾等方法
因產品需要展示相關時間,現總結如下方法:以供日后參考:
獲取每月有幾周
// 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 } // 該月天數 d.setFullYear(2018, 7, 0) const dd = d.getDate() // 該月第一個周一 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}獲得當前日期在當月第幾周
// a: 年 b: 月 c: 日 (不包括跟上個月重合的部分) 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 ) }總結
以上所述是小編給大家介紹的JS獲取月的第幾周和年的第幾周實例代碼 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!
新聞熱點
疑難解答
圖片精選