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


当前回答

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

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

其他回答

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

以下是我的解决方案:

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

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

一个只有数学计算的例子,没有任何Date函数。

const date = new date (); Const ts = +日期; const mondayTS = ts % (60 * 60 * 24 * (7-4) * 1000); const monday =新的日期(星期一); console.log(monday.toISOString(), 'Day:', monday.getDay());

const formatTS = v => new Date(v).toISOString(); const adjust = (v, d = 1) => v - v % (d * 1000); const d = new Date('2020-04-22T21:48:17.468Z'); const ts = +d; // 1587592097468 const test = v => console.log(formatTS(adjust(ts, v))); test(); // 2020-04-22T21:48:17.000Z test(60); // 2020-04-22T21:48:00.000Z test(60 * 60); // 2020-04-22T21:00:00.000Z test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday // So, what does `(7-4)` mean? // 7 - days number in the week // 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second. // new Date(0) ---> 1970-01-01T00:00:00.000Z // new Date(0).getDay() ---> 4

CMS的答案是正确的,但假设星期一是一周的第一天。 钱德勒·兹沃勒的答案是正确的,但摆弄了日期原型。 其他加/减小时/分钟/秒/毫秒的答案是错误的,因为不是所有的日子都有24小时。

下面的函数是正确的,它将日期作为第一个参数,将所需的一周第一天作为第二个参数(0表示周日,1表示周一,等等)。注意:小时、分、秒设置为0才有一天的开始。

function firstDayOfWeek(dateObject, firstDayOfWeekIndex) { const dayOfWeek = dateObject.getDay(), firstDayOfWeek = new Date(dateObject), diff = dayOfWeek >= firstDayOfWeekIndex ? dayOfWeek - firstDayOfWeekIndex : 6 - dayOfWeek firstDayOfWeek.setDate(dateObject.getDate() - diff) firstDayOfWeek.setHours(0,0,0,0) return firstDayOfWeek } // August 18th was a Saturday let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1) // outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200" // (may vary according to your time zone) document.write(lastMonday)

该函数使用当前毫秒时间减去当前周,如果当前日期是周一,则再减去一周(javascript从周日开始计数)。

function getMonday(fromDate) {
    // length of one day i milliseconds
  var dayLength = 24 * 60 * 60 * 1000;

  // Get the current date (without time)
    var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());

  // Get the current date's millisecond for this week
  var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);

  // subtract the current date with the current date's millisecond for this week
  var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);

  if (monday > currentDate) {
    // It is sunday, so we need to go back further
    monday = new Date(monday.getTime() - (dayLength * 7));
  }

  return monday;
}

当一周从一个月延伸到另一个月(也包括几年)时,我对它进行了测试,它似乎可以正常工作。