js判断当前日期输chu二十四节气的哪一个

// 二十四节气
function getSolarTerm() {
    const terms = ["小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨",
        "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑",
        "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至"
    ];

    // 每个节气对应的C值(21世纪参数,取自网页1)
    const C_VALUES = [5.4055, 20.12, 5.63, 20.646, 4.81, 20.1, 5.52, 21.04,
        5.678, 21.37, 7.108, 22.83, 7.5, 23.13, 7.646, 23.042,
        8.318, 23.438, 7.438, 22.36, 7.18, 21.94, 6.11, 5.4055
    ];

    const now = new Date();
    const year = now.getFullYear();
    const y = year % 100; // 取年份后两位
    const month = now.getMonth() + 1; // 当前月份(1-12)
    const date = now.getDate();

    // 计算某节气在当月的日期(网页1中的公式)
    const calcDay = (termIndex) => {
        const C = C_VALUES[termIndex];
        const L = Math.floor((year - (termIndex < 2 ? 1901 : 1900)) / 4); // 闰年修正
        return Math.abs(Math.floor(y * 0.2422 + C) - L);
    };

    // 获取当前月的两个节气索引(网页16中的月份对应逻辑)
    const term1Index = (month - 1) * 2; // 当月第一个节气索引(如3月对应惊蛰=4)
    const term2Index = term1Index + 1; // 当月第二个节气索引(如3月对应春分=5)

    // 计算两个节气的日期(添加时区补偿)
    const term1Day = calcDay(term1Index);
    const term2Day = calcDay(term2Index);

    // 判断当前日期所属节气
    if (date >= term1Day) return terms[term2Index]; // 属于第一个节气
    if (date >= term2Day) return terms[term1Index]; // 属于第二个节气


    // 若都不满足,则属于上个月的第二个节气(如3月3日可能属于2月的大寒)
    const prevTermIndex = term1Index - 1;
    return prevTermIndex >= 0 ? terms[prevTermIndex] : "";
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容