如何根据JS中的当前日期确定第一个月是哪一天

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

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

javascript date
1个回答
0
投票
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]
© www.soinside.com 2019 - 2024. All rights reserved.