如何在Javascript中将第一个工作日设置为星期一?

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

我构建了一个完全基于日期的应用程序。现在,客户确实希望将星期一作为一周的第一天,我有大量基于日期的日历视图、日记视图、日志视图、计算等,并且始终将星期日视为一周的第一天,因为它是 Javascript 默认值。当您调用 Date 对象的 GetDay() 函数时,这是第 0 天。

我可以做些什么来将一周的第一天设置为星期一吗?

蒂!

javascript
3个回答
2
投票

如果您想将星期一作为第一天,您可以这样做:

const dayIndex = defaultDayIndex === 0 ? 6:默认DayIndex-1;

const myDate = new Date('2021-12-07');

const defaultDayIndex = myDate.getDay();
// make monday first day of the week and sunday the last day
// monday will be index 0, and sunday will be index 6
const dayIndex = defaultDayIndex === 0 ? 6 : defaultDayIndex-1;

0
投票
const weekMap = {
    1: 0, // → monday
    2: 1, // → tuesday
    3: 2, // → wednesday
    4: 3, // → thursday
    5: 4, // → friday
    6: 5, // → saturday
    0: 6, // → sunday
};

console.log(weekMap[(new Date()).getDay()]);

0
投票
const dayIndex = (new Date().getDay() + 6) % 7;
© www.soinside.com 2019 - 2024. All rights reserved.