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

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?

This question is related to javascript algorithm

The answer is


a more generalized version of this... this will give you any day in the current week based on what day you specify.

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


I'm using this

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

This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).

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

I have tested it when week spans over from one month to another (and also years), and it seems to work properly.


Check out Date.js

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

Check out: moment.js

Example:

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)

Bonus: works with node.js too


CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that play with hour/minutes/seconds/milliseconds are wrong.

The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.

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


setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.

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

Here is my solution:

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

Now you can pick date by returned array index.


An example of the mathematically only calculation, without any Date functions.

_x000D_
_x000D_
const date = new Date();_x000D_
const ts = +date;_x000D_
_x000D_
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);_x000D_
_x000D_
const monday = new Date(mondayTS);_x000D_
console.log(monday.toISOString(), 'Day:', monday.getDay());
_x000D_
_x000D_
_x000D_

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


Not sure how it compares for performance, but this works.

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

Or as a function:

# modifies _date_
function setToMonday( date ) {
    var day = date.getDay() || 7;  
    if( day !== 1 ) 
        date.setHours(-24 * (day - 1)); 
    return date;
}

setToMonday(new Date());

Good evening,

I prefer to just have a simple extension method:

Date.prototype.startOfWeek = function (pStartOfWeek) {
    var mDifference = this.getDay() - pStartOfWeek;

    if (mDifference < 0) {
        mDifference += 7;
    }

    return new Date(this.addDays(mDifference * -1));
}

You'll notice this actually utilizes another extension method that I use:

Date.prototype.addDays = function (pDays) {
    var mDate = new Date(this.valueOf());
    mDate.setDate(mDate.getDate() + pDays);
    return mDate;
};

Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:

var mThisSunday = new Date().startOfWeek(0);

Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:

var mThisMonday = new Date().startOfWeek(1);

Regards,


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

This will work well.


First Day of The Week

To get the date of the first day of the week from today, you can use something like so:

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

Or to get the last day of the week from today:

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

* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.

* You can also format it using toISOString method like so: getLastSunday().toISOString()