function isDateInThisWeek(date) {
const todayObj = new Date();
const todayDate = todayObj.getDate();
const todayDay = todayObj.getDay();
// get first date of week
const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));
// get last date of week
const lastDayOfWeek = new Date(firstDayOfWeek);
lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);
// if date is equal or within the first and last dates of the week
return date >= firstDayOfWeek && date <= lastDayOfWeek;
}
const date = new Date();
const isInWeek = isDateInThisWeek(date);
2条答案
按热度按时间ql3eal8s1#
日期是困难的,我总是建议使用专门用于日期处理的库,因为它降低了代码中出错的可能性。
MomentJS是一个很好的选择。
编辑:请注意,截至2020年,Moment可能不是新项目的良好选择
d7v8vwbk2#
这似乎对我很管用。