如何在JavaScript中计算农历新年的日期?

7nbnzgx9  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(131)

我需要在中国日历的一年开始日期,因为我们在西方使用的一年(公历)。
我如何在代码中实现这一点,最有用的JS,但任何方法都可以,或者如果没有,有人有一个列表,我可以把他们放在一个数据库?
谢谢

r7s23pms

r7s23pms1#

如何使用这个JS库:是吗

dsekswqp

dsekswqp2#

如果你不想要一个完整的库,使用我今天做的这个片段:

function get_new_moons(date) {
    const LUNAR_MONTH = 29.5305888531  // https://en.wikipedia.org/wiki/Lunar_month
    let y = date.getFullYear()
    let m = date.getMonth() + 1  // https://stackoverflow.com/questions/15799514/why-does-javascript-getmonth-count-from-0-and-getdate-count-from-1
    let d = date.getDate()
    // https://www.subsystems.us/uploads/9/8/9/4/98948044/moonphase.pdf
    if (m <= 2) {
        y -= 1
        m += 12
    }
    a = Math.floor(y / 100)
    b = Math.floor(a / 4)
    c = 2 - a + b
    e = Math.floor(365.25 * (y + 4716))
    f = Math.floor(30.6001 * (m + 1))
    julian_day = c + d + e + f - 1524.5
    days_since_last_new_moon = julian_day - 2451549.5
    new_moons = days_since_last_new_moon / LUNAR_MONTH
    days_into_cycle = (new_moons % 1) * LUNAR_MONTH
    return new_moons
}

function in_chinese_new_year(date) {
    /* The date is decided by the Chinese Lunar Calendar, which is based on the
    cycles of the moon and sun and is generally 21–51 days behind the Gregorian
    (internationally-used) calendar. The date of Chinese New Year changes every
    year, but it always falls between January 21st and February 20th. */
    return Math.floor(get_new_moons(date)) > Math.floor(get_new_moons(new Date(date.getFullYear(), 0, 20))) ? 1 : 0
}

function get_chinese_new_year(gregorian_year) {
    // Does not quite line up with https://www.travelchinaguide.com/essential/holidays/new-year/dates.htm
    for (let i = 0; i <= 30; ++i) {
        let start = new Date(gregorian_year, 0, 1)
        start.setDate(21 + i)
        if(in_chinese_new_year(start)) return start
    }
}

用法:

>>> get_chinese_new_year(2023)
Sun Jan 22 2023 00:00:00 GMT+0100 (Midden-Europese standaardtijd)

相关问题