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


当前回答

晚上好,

我更喜欢有一个简单的扩展方法:

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);

问候,

其他回答

查看:moment.js

例子:

moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)

好处:也适用于node.js

不知道它的性能如何,但这是可行的。

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());

周一上午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 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;
}

我用这个:

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;
}

它工作得很好。