如何在JS中不使用new Date()根据当前日期判断当月1号是哪一天

问题描述 投票:0回答:2

鉴于 2024 年 5 月 18 日是星期六,如何在不使用 new Date() 的情况下确定 5 月 1 日是哪一天?

编辑: 我提供的答案应该适用于周日索引为 0 的所有编程语言。由于我在 SO 中找不到答案,所以我决定精心制作这个答案,以便帮助未来可能会提出以下问题的开发人员。

我添加“without new Date()”的原因是为了防止SO用户回答

new Date(2024, 4, 1).getDay()
,这增加了一层处理过程。除了以下答案之外,如果有更好的算法,请随时提供,以便我们为 SO 做出贡献。

javascript algorithm date
2个回答
1
投票
const cur_date = 18
const cur_day = 6 // 0 - Sun, ..., 6 - Sat
const days = ['sun', 'mon', 'tue', 'wed', 'thur', 'fri', 'sat']
const res = cur_day - cur_date % 7 + 1 // Number can be reset by +7 if value is negative.
console.log(days.at(res))

当您对

cur_date
取模 7 时,结果将返回到星期六的最早日期,即 4。然后,您从当天本身 (6 - 4) 中扣除,将返回 2(星期二)。为了抵消这一点,您需要+ 1。

以下是 2024 年 5 月日历的示例。

[SUN][MON][TUE][WED][THU][FRI][SAT]
[xx] [xx] [xx] [01] [02] [03] [04]
[05] [06] [07] [08] [09] [10] [11]
[12] [13] [14] [15] [16] [17] [18]
[19] [20] [21] [22] [23] [24] [25]
[26] [27] [28] [29] [30] [31] [xx]

0
投票

我们知道还有7天:

let days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

我们还知道5月18日是星期六,即:

days[days.indexOf('Saturday')] === 5

我们还知道 5 月 18 日 - 5 月 1 日 = 17 天

(5 - 17) % 7 === -5

属于 2 的模类,因为 -5 + 7 === 2,因此 5 月 1 日是

days[2]
,这是星期三。

但是未来 5 月 1 日会发生在什么时候呢?如果我们忽略闰年,那么公式将是

days[(7 + ((2 + (numberOfYears * 365)) % 7)) % 7]
,(我们以 7 为模,将 7 添加到结果中,然后再次以 7 为模来处理负数),但我们也需要考虑闰年,即每个闰年4年了,就像这样:

function compute(numberOfYears) {
    let dayWithoutLeapYears = (7 + ((2 + (numberOfYears * 365)) % 7)) % 7;
    let start = 2024;
    while (numberOfYears !== 0) {
        let direction = ((numberOfYears < 0) ? -1 : 1); 
        numberOfYears -= direction;
        start += direction;
        if ((start % 4) === 0) {
            dayWithoutLeapYears += direction;
        }
    }
    dayWithoutLeapYears = (7 + dayWithoutLeapYears) % 7;
    return (dayWithoutLeapYears);
}

let days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

document.getElementById("number").addEventListener("input", function() {
    document.getElementById("result").innerText = days[compute(this.value)];
});
<input type="number" value="0" id="number">
<div id="result"></div>

© www.soinside.com 2019 - 2024. All rights reserved.