jyzwf / blog

在Issues里记录技术得点滴
17 stars 3 forks source link

获得一年中某一周的日期集合 #40

Open jyzwf opened 6 years ago

jyzwf commented 6 years ago
/**
 * 
 * @param {*Nunmer} year 
 * @param {*Number} week 
 */
const findDaysInWeek = (year, week) => {
    if (isOverYearWeeks(year, week)) {
        throw new Error('输入的周数大于该年的总周数')
    }

    var daysInWeek = [], // 记录每周里面的日期集合
        oneDayMs = 24 * 3600 * 1000

    var firstDayWeekMs = firstDayWeek(year, true)

    for (var i = (week - 1) * 7; i < 7 * week; i++) {
        let d = firstDayWeekMs + i * oneDayMs
        daysInWeek.push(new Date(d))
    }

    return daysInWeek
}

// 获取一年中有几周
/**
 * 
 * @param {*Number} year 
 */
const weeksOfYear = year => {
    var yearDays = getDayCountOfYear(year, true)
    var firstDayOfYear = new Date(year, 0, 1)

    return Math.ceil((yearDays - firstDayOfYear.getDay()) / 7.0)
}

// 是否超过该年的总周数
/**
 * 
 * @param {*Number} year 
 * @param {*Number} week 
 */
const isOverYearWeeks = (year, week) => {
    var totalWeeks = weeksOfYear(year)

    return week > totalWeeks
}

// 判断是否是瑞年
/**
 * 
 * @param {*Number} year 
 * @param {*Boolean} isDays 
 */
const getDayCountOfYear = (year, isDays) => {
    const isLeapYear = year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0);
    return isDays ?
        (isLeapYear ? 366 : 365) :
        isLeapYear
};

// 获取一年中第一周第一天(这里的第一天指周日)是几号或者该天距离 1970年1月1日00:00:00 (世界标准时间) 起经过的毫秒数。
/**
 * 
 * @param {*Number} year 
 * @param {*Boolean} isMs 
 */
const firstDayWeek = (year, isMs) => {
    var oneDayMs = 24 * 3600 * 1000,
        firstDayOfYear = new Date(year, 0, 1),
        firstDayOfYear_day = firstDayOfYear.getDay(), // 获取一年中1月1号是星期几

        preDaysInWeek = -firstDayOfYear_day, //1月1号该周前面还有几天
        firstDayWeekMs = firstDayOfYear.getTime() + preDaysInWeek * oneDayMs // 第一周是几号

    return isMs ? firstDayWeekMs : new Date(firstDayWeekMs)
}

findDaysInWeek(2018, 1)