上周日为开始日,本周六为结束日,这一周在一年中的所在周数

发布时间 2023-04-23 17:49:45作者: Z-HarOld
function getWeekNumber(date) {
            // 创建表示周日的新 Date 对象并获取其时间戳
            const sunday = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
            const sundayTimestamp = sunday.getTime();

            // 计算到本周六的时间跨度并转换为天数
            const saturdayTimespan = 6 * 24 * 3600 * 1000; // 6天的时间跨度
            const saturdayTimestamp = sundayTimestamp + saturdayTimespan;
            const daysSinceStartOfYear = Math.floor((saturdayTimestamp - new Date(date.getFullYear(), 0, 1).getTime()) / (24 * 3600 * 1000));

            // 计算本周在一年中的周数
            const weekNumber = Math.ceil(daysSinceStartOfYear / 7);
            console.log(weekNumber)
            return weekNumber;
        }

        // 示例用法
        const myDate = new Date(2023, 0, 2); // 周日    ***注意:月分是从0开始的{0-11}  对应月份是--{1-12}*****
        const weekNumber = getWeekNumber(myDate); // weekNumber 等于 16

凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数凑凑字数