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


当前回答

简单的解决办法,得到一周的第一天。

使用这种解决方案,可以设置任意的星期开始(例如,星期日= 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()中相同的常量

其他回答

我在用这个

function get_next_week_start() {
   var now = new Date();
   var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
   return next_week_start;
}

扩展回答来自@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.js

Date.today().previous().monday()

区分本地时间和UTC时间是很重要的。我想用UTC找到一周的开始,所以我使用了下面的函数。

function start_of_week_utc(date, start_day = 1) {

// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.

    date = new Date(date);
    const day_of_month = date.getUTCDate();
    const day_of_week = date.getUTCDay();
    const difference_in_days = (
        day_of_week >= start_day
        ? day_of_week - start_day
        : day_of_week - start_day + 7
    );
    date.setUTCDate(day_of_month - difference_in_days);
    date.setUTCHours(0);
    date.setUTCMinutes(0);
    date.setUTCSeconds(0);
    date.setUTCMilliseconds(0);
    return date;
}

要在给定时区中找到一周的开始,首先将时区偏移量添加到输入日期,然后从输出日期中减去时区偏移量。

const local_start_of_week = new Date(
    start_of_week_utc(
        date.getTime() + timezone_offset_ms
    ).getTime() - timezone_offset_ms
);

简单的解决办法,得到一周的第一天。

使用这种解决方案,可以设置任意的星期开始(例如,星期日= 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()中相同的常量