获取某年多少周

260 阅读1分钟

获取每年有多少周,例如2018年有53周,2019年52周

function getNumOfWeeks (year) {
    year = Number(year)
    if (isNaN(year)) return ''
    // 获取这一年的第一天是星期几
    let week = new Date(year, 0, 1).getDay()

    // 闰年366天、平年365天
    let days = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) ? 366 : 365
    if (week === 1) {
        // 如果第一号是周一
        return Math.ceil(days / 7)
    } else {
        // 如果不是周一
        return Math.ceil((days - 7 + week) / 7)
    }
}