繁体   English   中英

JavaScript - 从当前日期获取一周的第一天

[英]JavaScript - get the first day of the week from current date

我需要最快的方法来获得一周的第一天。 例如:今天是11月11日,星期四; 我想要本周的第一天,即 11 月 8 日和星期一。 我需要 MongoDB map function 的最快方法,有什么想法吗?

使用 Date 对象的getDay方法,您可以知道一周中的第几天(例如 0=星期日、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

不确定它如何比较性能,但这有效。

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

CMS 的回答是正确的,但假设星期一是一周的第一天。
Chandler Zwolle 的回答是正确的,但摆弄了 Date 原型。
其他添加/减去小时/分钟/秒/毫秒的答案是错误的,因为并非所有日子都有 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)

查看Date.js

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

一周的第一天/最后一天

要获得即将到来的一周的第一天,您可以使用以下内容:

 function getUpcomingSunday() { const date = new Date(); const today = date.getDate(); const currentDay = date.getDay(); const newDate = date.setDate(today - currentDay + 7); return new Date(newDate); } console.log(getUpcomingSunday());

或获取最新的第一天:

 function getLastSunday() { const date = new Date(); const today = date.getDate(); const currentDay = date.getDay(); const newDate = date.setDate(today - (currentDay || 7)); return new Date(newDate); } console.log(getLastSunday());

* 根据您所在的时区,一周的开始不必从星期日开始,它可以从星期五、星期六、星期一或您的机器设置的任何其他日期开始。 这些方法将解释这一点。

* 您也可以使用toISOString方法格式化它,如下所示: getLastSunday().toISOString()

var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));

这将运作良好。

我正在使用这个

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

此函数使用当前毫秒时间减去当前星期,如果当前日期是星期一,则再减去一周(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;
}

当一周从一个月跨越到另一个(甚至几年)时,我已经对其进行了测试,并且它似乎可以正常工作。

晚上好,

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

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

问候,

setDate() 存在上述评论中提到的月份边界问题。 一个干净的解决方法是使用纪元时间戳而不是 Date 对象上的(令人惊讶的违反直觉的)方法来查找日期差异。 IE

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 = +date; const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000); const monday = new Date(mondayTS); 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

一个更通用的版本......这将根据您指定的日期为您提供当前一周中的任何一天。

 //returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday function getRelativeDayInWeek(d,dy) { d = new Date(d); var day = d.getDay(), diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday return new Date(d.setDate(diff)); } var monday = getRelativeDayInWeek(new Date(),1); var friday = getRelativeDayInWeek(new Date(),5); console.log(monday); console.log(friday);

返回星期一 00am 到星期一 00am。

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)

获得一周第一天的简单解决方案。

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

我用这个:

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

接受的答案不适用于在 UTC-XX:XX 时区运行代码的任何人。

这是仅适用于日期的代码,无论时区如何。 如果您也提供时间,这将不起作用。 仅提供日期或解析日期并将其作为输入提供。 我在代码开头提到了不同的测试用例。

 function getDateForTheMonday(dateString) { var orignalDate = new Date(dateString) var modifiedDate = new Date(dateString) var day = modifiedDate.getDay() diff = modifiedDate.getDate() - day + (day == 0? -6:1);// adjust when day is sunday modifiedDate.setDate(diff) var diffInDate = orignalDate.getDate() - modifiedDate.getDate() if(diffInDate == 6) { diff = diff + 7 modifiedDate.setDate(diff) } console.log("Given Date: " + orignalDate.toUTCString()) console.log("Modified date for Monday: " + modifiedDate) } getDateForTheMonday("2022-08-01") // Jul month with 31 Days getDateForTheMonday("2022-07-01") // June month with 30 days getDateForTheMonday("2022-03-01") // Non leap year February getDateForTheMonday("2020-03-01") // Leap year February getDateForTheMonday("2022-01-01") // First day of the year getDateForTheMonday("2021-12-31") // Last day of the year

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

function可以这样

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

签出: 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM