我需要最快的方法得到一周的第一天。例如:今天是11月11日,是星期四;我想要这周的第一天,也就是11月8日,一个星期一。我需要MongoDB映射函数的最快方法,有什么想法吗?
当前回答
更普遍的说法是……这将根据您指定的日期给出当前一周中的任何一天。
//返回一周中的相对日期0 = Sunday, 1 = Monday…6 =星期六 函数getRelativeDayInWeek(d,dy) { d = new日期(d); var day = d.getDay(), diff = d.getDate() - day + (day == 0 ?6: dy);//当白天是星期天时进行调整 (d.setDate(diff)); } var monday = getRelativeDayInWeek(new Date(),1); var friday = getRelativeDayInWeek(new Date(),5); console.log(星期一); console.log(周五);
其他回答
一周的第一天/最后一天
为了得到即将到来的一周的第一天,你可以这样使用:
函数getUpcomingSunday() { const date = new date (); const today = date.getDate(); const currentDay = date.getDay(); const newDate =日期。setDate(今天- currentDay + 7); return newDate (newDate); } console.log (getUpcomingSunday ());
或者获得最晚的第一天:
函数getLastSunday() { const date = new date (); const today = date.getDate(); const currentDay = date.getDay(); const newDate =日期。setDate(今天- (currentDay || 7)); return newDate (newDate); } console.log (getLastSunday ());
*根据您所在的时区,一周的开始不必从周日开始,它可以从周五、周六、周一或您的机器设置的任何其他日子开始。这些方法可以解释。
*你也可以像这样使用toISOString方法格式化它:
晚上好,
我更喜欢有一个简单的扩展方法:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
你会注意到这实际上利用了我使用的另一个扩展方法:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
现在,如果你的周从周日开始,为pStartOfWeek参数传递一个“0”,如下所示:
var mThisSunday = new Date().startOfWeek(0);
类似地,如果你的周从星期一开始,为pStartOfWeek参数传递一个“1”:
var mThisMonday = new Date().startOfWeek(1);
问候,
更普遍的说法是……这将根据您指定的日期给出当前一周中的任何一天。
//返回一周中的相对日期0 = Sunday, 1 = Monday…6 =星期六 函数getRelativeDayInWeek(d,dy) { d = new日期(d); var day = d.getDay(), diff = d.getDate() - day + (day == 0 ?6: dy);//当白天是星期天时进行调整 (d.setDate(diff)); } var monday = getRelativeDayInWeek(new Date(),1); var friday = getRelativeDayInWeek(new Date(),5); console.log(星期一); console.log(周五);
不知道它的性能如何,但这是可行的。
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
或作为一个函数:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
简单的解决办法,得到一周的第一天。
使用这种解决方案,可以设置任意的星期开始(例如,星期日= 0,星期一= 1,星期二= 2,等等)。
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
解决方案正确地按月包装(由于使用了Date.setDate()) 对于startOfWeek,可以使用与Date.getDay()中相同的常量