我需要最快的方法得到一周的第一天。例如:今天是11月11日,是星期四;我想要这周的第一天,也就是11月8日,一个星期一。我需要MongoDB映射函数的最快方法,有什么想法吗?


当前回答

扩展回答来自@Christian C. Salvadó和来自@Ayyash(对象是可变的)和@Awi和@Louis Ameline(设置时间为00:00:00)的信息

函数可以是这样的

function getMonday(d) {
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
  d.setDate(diff);
  d.setHours(0,0,0,0); // set hours to 00:00:00

  return d; // object is mutable no need to recreate object
}

getMonday(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()中相同的常量

扩展回答来自@Christian C. Salvadó和来自@Ayyash(对象是可变的)和@Awi和@Louis Ameline(设置时间为00:00:00)的信息

函数可以是这样的

function getMonday(d) {
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
  d.setDate(diff);
  d.setHours(0,0,0,0); // set hours to 00:00:00

  return d; // object is mutable no need to recreate object
}

getMonday(new Date())

使用Date对象的getDay方法,您可以知道一周中的天数(0=星期日,1=星期一,等等)。

然后你可以用这个天数加1,例如:

function getMonday(d) {
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
  return new Date(d.setDate(diff));
}

getMonday(new Date()); // Mon Nov 08 2010

周一上午00点到周一上午00点返回。

const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)

以下是我的解决方案:

function getWeekDates(){
    var day_milliseconds = 24*60*60*1000;
    var dates = [];
    var current_date = new Date();
    var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
    var sunday = new Date(monday.getTime()+6*day_milliseconds);
    dates.push(monday);
    for(var i = 1; i < 6; i++){
        dates.push(new Date(monday.getTime()+i*day_milliseconds));
    }
    dates.push(sunday);
    return dates;
}

现在你可以通过返回的数组索引来选择日期。