0
点赞
收藏
分享

微信扫一扫

今天是今年第几周(周一开始算起)

雅典娜的棒槌 2022-01-06 阅读 48
javascript
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        String.prototype.weekIndexInYear = function () {
            var nowDate = new Date(this != '' ? this : new Date());
            var initTime = new Date(this != '' ? this : new Date());
            initTime.setMonth(0); // 本年初始月份
            initTime.setDate(1); // 本年初始时间
            initTime.setHours(0);
            initTime.setMinutes(0);
            initTime.setSeconds(0);

            nowDate.setHours(23);
            nowDate.setMinutes(59);
            nowDate.setSeconds(59);
            var differenceVal = nowDate - initTime; // 今天的时间减去本年开始时间,获得相差的时间
            var todayYear = Math.ceil(differenceVal / (24 * 60 * 60 * 1000)); // 获取今天是今年第几天
            console.log('今年的第几天?',todayYear);
            /* 周日为第一周的算法 */
            // return Math.ceil(todayYear / 7)

            /* 周一为第一周的算法 */
            var firstDay = initTime.getDay(); // 获取这年的第一天是周几,因为首周可能是上一年的最后一周内
            // console.log('今年第一天是周几',firstDay);
            var startDiff;
            if (firstDay === 0) {
                startDiff = 1;
            } else if (firstDay === 1) { // 第一天是周一
                startDiff = 0;
            } else {
                startDiff = 7 - firstDay + 1;
            }
            return parseInt(Math.ceil((todayYear - startDiff) / 7)); // 返回今天是今年第几周
        };
         let index = new Date('1/3/2022').toLocaleDateString().weekIndexInYear()
         console.log('今年第几周',index);

    </script>
</body>

</html>
举报

相关推荐

0 条评论