获取自然周数的下拉列表

需要引用第三方的day.js库,设定了只显示过去60天的周数,可自行修改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自然周数下拉列表</title>
    <script src="/js/day.1.11.12.js"></script>
</head>
<body>
<select id="ddlWeeks"></select>
<script>
    function getWeekNumber(date) {
        var d = new Date(date);
        d.setHours(0, 0, 0);
        d.setDate(d.getDate() + 4 - (d.getDay() || 7));
        var yearStart = new Date(d.getFullYear(), 0, 1);
        var weekNo = Math.ceil(((d - yearStart) / 86400000) / 7);
        return weekNo;
    }
    function populateWeekDropdown(year) {
        var select = document.getElementById('ddlWeeks');
        var numWeeks = new Date(year, 11, 31).getDay() === 4 || new Date(year, 11, 31).getDay() === 5 ? 54 : 53;
        for (var i = 1; i <= numWeeks; i++) {
            var weekNumber = i < 10 ? '0' + i : i;
            var start_end = getWeekStartAndEndDate(year, weekNumber);
            var start = start_end.start;
            var end = start_end.end;
            if (daysBetween(start, new Date()) > 60) {
                continue;
            }
            var option = document.createElement('option');
            option.value = dayjs(start).format("YYYY-MM-DD");//year + 'W' + weekNumber;
            option.text = weekNumber + "周:" + dayjs(start).format("YY-MM-DD");
            select.appendChild(option);
            if (end > new Date()) {
                break;
            }
        }
    }

    function daysBetween(date1, date2) {
        const oneDay = 86400000; // 一天的毫秒数
        const date1Ms = date1.getTime(); // 将日期转换为时间戳
        const date2Ms = date2.getTime(); // 同上
        // 计算两个日期之间相差的毫秒数
        const diff = Math.abs(date1Ms - date2Ms); 
        // 将毫秒数转换为天数
        return Math.round(diff / oneDay); 
    }

    function getWeekStartAndEndDate(year, weekNumber) {
        const date = new Date(year, 0, 1); // 获取该年份的第一天
        const dayOfWeek = date.getDay() || 7; // 获取第一天是星期几(‌周日为7,‌周一为1,‌以此类推)‌
        const offset = date.getDate() - dayOfWeek + (weekNumber - 1) * 7 + 1; // 计算该周第一天的日期偏移量
        const start = new Date(date.setDate(offset)); // 设置起始日期
        const end = new Date(start); // 复制起始日期对象
        end.setDate(start.getDate() + 6); // 设置结束日期为起始日期加6天
        return { start, end };
    }


    var currentYear = new Date().getFullYear();
    var curMonth = new Date().getMonth();
    if (curMonth <= 1) {
        populateWeekDropdown(currentYear - 1);
    }
    populateWeekDropdown(currentYear);
</script>

</body>
</html>

 

posted @ 2024-08-04 08:21  猫狼  阅读(6)  评论(0编辑  收藏  举报