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


当前回答

我用这个:

let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);

// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

它工作得很好。

其他回答

区分本地时间和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()中相同的常量

查看Date.js

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

setDate()在月份边界上有问题,在上面的注释中已经注意到。一个简单的解决方法是使用epoch时间戳来查找日期差异,而不是使用date对象上的方法(令人惊讶地违反直觉)。即。

function getPreviousMonday(fromDate) {
    var dayMillisecs = 24 * 60 * 60 * 1000;

    // Get Date object truncated to date.
    var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));

    // If today is Sunday (day 0) subtract an extra 7 days.
    var dayDiff = d.getDay() === 0 ? 7 : 0;

    // Get date diff in millisecs to avoid setDate() bugs with month boundaries.
    var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;

    // Return date as YYYY-MM-DD string.
    return new Date(mondayMillisecs).toISOString().slice(0, 10);
}

更普遍的说法是……这将根据您指定的日期给出当前一周中的任何一天。

//返回一周中的相对日期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(周五);