[javascript] How to get first and last day of the current week in JavaScript

I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?

This question is related to javascript date

The answer is


You could do something like this

var today = new Date();
var startDay = 0; 
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);

Where startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).


_x000D_
_x000D_
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
_x000D_
_x000D_
_x000D_

I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.

if i remove .toUTCString(). output which i receive is not as expected


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 be useful for any date scenario.


Here's a quick way to get first and last day, for any start day. knowing that:

1 day = 86,400,000 milliseconds.

JS dates values are in milliseconds

Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.

var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day

Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.

var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

function getFirstDayOfWeek(date, from) {
    //Default start week from 'Sunday'. You can change it yourself.
    from = from || 'Sunday'; 
    var index = weekday.indexOf(from);
    var start = index >= 0 ? index : 0;

    var d = new Date(date);
    var day = d.getDay();
    var diff = d.getDate() - day + (start > day ? start - 7 : start);
    d.setDate(diff);
    return d;
};

Last day of week is just 6 days after first day of week

function getLastDayOfWeek(date, from) {
    from = from || 'Sunday';
    var index = weekday.indexOf(from);
    var start = index >= 0 ? index : 0;

    var d = new Date(date);
    var day = d.getDay();
    var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
    d.setDate(diff);
    return d;
};

Test:

getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017

You can also use following lines of code to get first and last date of the week:

var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));

Hope it will be useful..


JavaScript

function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
  var cd = curr.getDate() - curr.getDay();
  var from = new Date(curr.setDate(cd + firstDay));
  var to = new Date(curr.setDate(cd + 6 + firstDay));

  return {
    from,
    to,
  };
};

TypeScript

export enum WEEK_DAYS {
  Sunday = 0,
  Monday = 1,
  Tuesday = 2,
  Wednesday = 3,
  Thursday = 4,
  Friday = 5,
  Saturday = 6,
}

export const getWeekDays = (
  curr: Date,
  firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
  const cd = curr.getDate() - curr.getDay();
  const from = new Date(curr.setDate(cd + firstDay));
  const to = new Date(curr.setDate(cd + 6 + firstDay));

  return {
    from,
    to,
  };
};

I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.

Simply to get current date time in specific format

        case 'Today':
        moment().format("DD/MM/YYYY h:mm A");

        case 'This Week':
          moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");

Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.

        case 'This Month':
          moment().endOf('month').format("DD/MM/YYYY h:mm A");

        case 'This Quarter':
          moment().endOf('quarter').format("DD/MM/YYYY h:mm A");

I chose this format as per my need. You can change the format according to your requirement.


SetDate will sets the day of the month. Using setDate during start and end of the month,will result in wrong week

var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014

If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014

So overcome this issue i used

var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(curr.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week

Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016. For this reason I think, the correct calculation should be like the below simply;

var d = new Date(),
    dayInMs = 1000 * 60 * 60 * 24,
    weekInMs = dayInMs * 7,
    startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
    todayElapsedTime = d.valueOf() - startOfToday,
    dayDiff = d.getDay() * dayInMs,
    dateDiff = dayDiff + todayElapsedTime, 
    // finally
    startOfWeek = d.valueOf() - dateDiff,
    endOfWeek = startOfWeek + weekInMs - 1;

Small change to @Chris Lang answer. if you want Monday as the first day use this.

Date.prototype.GetFirstDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());

Thaks @Chris Lang


        //get start of week; QT
    function _getStartOfWeek (date){
        var iDayOfWeek = date.getDay();
        var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ?  -6:1);

        return new Date(date.setDate(iDifference));
    }, 

    function _getEndOfWeek(date){
        return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
    }, 

*current date == 30.06.2016 and monday is the first day in week.

It also works for different months and years. Tested with qunit suite:

enter image description here

        QUnit.module("Planung: Start of week");
    QUnit.test("Should return start of week based on current date", function (assert) {
        var startOfWeek = Planung._getStartOfWeek(new Date());
        assert.ok( startOfWeek , "returned date: "+ startOfWeek);
    });

    QUnit.test("Should return start of week based on a sunday date", function (assert) {
        var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
        assert.ok( startOfWeek , "returned date: "+ startOfWeek);
    });

    QUnit.test("Should return start of week based on a monday date", function (assert) {
        var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
        assert.ok( startOfWeek , "returned date: "+ startOfWeek);
    });

    QUnit.module("Planung: End of week");
    QUnit.test("Should return end of week based on current date", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date());
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on monday date with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });

An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.

For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.

The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):

if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
  // d is in same week as d1
}

or in the current week starting on Sunday:

if (d >= startOf('week') && d <= endOf('week')) {
  // d is in the current week
}

_x000D_
_x000D_
// Returns a new Date object set to start of given unit_x000D_
// For start of week, accepts any day as start_x000D_
function startOf(unit, date = new Date(), weekStartDay = 0) {_x000D_
  // Copy original so don't modify it_x000D_
  let d = new Date(date);_x000D_
  let e = new Date(d);_x000D_
  e.setHours(23,59,59,999);_x000D_
  // Define methods_x000D_
  let start = {_x000D_
    second: d => d.setMilliseconds(0),_x000D_
    minute: d => d.setSeconds(0,0),_x000D_
    hour  : d => d.setMinutes(0,0,0),_x000D_
    day   : d => d.setHours(0,0,0,0),_x000D_
    week  : d => {_x000D_
      start.day(d);_x000D_
      d.setDate(d.getDate() - d.getDay() + weekStartDay);_x000D_
      if (d > e) d.setDate(d.getDate() - 7);_x000D_
    },_x000D_
    month : d => {_x000D_
      start.day(d);_x000D_
      d.setDate(1);_x000D_
    },_x000D_
    year  : d => {_x000D_
      start.day(d);_x000D_
      d.setMonth(0, 1);_x000D_
    },_x000D_
    decade: d => {_x000D_
      start.year(d);_x000D_
      let year = d.getFullYear();_x000D_
      d.setFullYear(year - year % 10);_x000D_
    },_x000D_
    century: d => {_x000D_
      start.year(d);_x000D_
      let year = d.getFullYear();_x000D_
      d.setFullYear(year - year % 100);_x000D_
    },_x000D_
    millenium: d => {_x000D_
      start.year(d);_x000D_
      let year = d.getFullYear();_x000D_
      d.setFullYear(year - year % 1000);_x000D_
    }_x000D_
  }_x000D_
  start[unit](d);_x000D_
  return d;_x000D_
}_x000D_
_x000D_
// Returns a new Date object set to end of given unit_x000D_
// For end of week, accepts any day as start day_x000D_
// Requires startOf_x000D_
function endOf(unit, date = new Date(), weekStartDay = 0) {_x000D_
  // Copy original so don't modify it_x000D_
  let d = new Date(date);_x000D_
  let e = new Date(date);_x000D_
  e.setHours(23,59,59,999);_x000D_
  // Define methods_x000D_
  let end = {_x000D_
    second: d => d.setMilliseconds(999),_x000D_
    minute: d => d.setSeconds(59,999),_x000D_
    hour  : d => d.setMinutes(59,59,999),_x000D_
    day   : d => d.setHours(23,59,59,999),_x000D_
    week  : w => {_x000D_
      w = startOf('week', w, weekStartDay);_x000D_
      w.setDate(w.getDate() + 6);_x000D_
      end.day(w);_x000D_
      d = w;_x000D_
    },_x000D_
    month : d => {_x000D_
      d.setMonth(d.getMonth() + 1, 0);_x000D_
      end.day(d);_x000D_
    },  _x000D_
    year  : d => {_x000D_
      d.setMonth(11, 31);_x000D_
      end.day(d);_x000D_
    },_x000D_
    decade: d => {_x000D_
      end.year(d);_x000D_
      let y = d.getFullYear();_x000D_
      d.setFullYear(y - y % 10 + 9);_x000D_
    },_x000D_
    century: d => {_x000D_
      end.year(d);_x000D_
      let y = d.getFullYear();_x000D_
      d.setFullYear(y - y % 100 + 99);_x000D_
    },_x000D_
    millenium: d => {_x000D_
      end.year(d);_x000D_
      let y = d.getFullYear();_x000D_
      d.setFullYear(y - y % 1000 + 999);_x000D_
    }_x000D_
  }_x000D_
  end[unit](d);_x000D_
  return d;_x000D_
}_x000D_
_x000D_
// Examples_x000D_
let d = new Date();_x000D_
_x000D_
['second','minute','hour','day','week','month','year',_x000D_
 'decade','century','millenium'].forEach(unit => {_x000D_
   console.log(('Start of ' + unit).padEnd(18)  + ': ' +_x000D_
   startOf(unit, d).toString());_x000D_
   console.log(('End of ' + unit).padEnd(18)  + ': ' +_x000D_
   endOf(unit, d).toString());_x000D_
});
_x000D_
_x000D_
_x000D_


The excellent (and immutable) date-fns library handles this most concisely:

const start = startOfWeek(date);
const end = endOfWeek(date);

Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:

const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});

Nice suggestion but you got a small problem in lastday. You should change it to:

lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.

    let startOfWeek = moment().startOf("isoWeek").toDate();
    let endOfWeek = moment().endOf("isoWeek").toDate();

krtek's method has some wrong,I tested this

var startDay = 0; 
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);

it works


We have added jquery code that shows the current week of days from monday to sunday.

var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
    let first = d.getDate() - d.getDay() + i; 
    let dt = new Date(d.setDate(first));
    var _day = _days[dt.getDay()];
     var _month = _months[dt.getMonth()];
     var _date = dt.getDate();
     if(_date < 10 ){
         _date = '0' +_date;
     }
     var _year = dt.getFullYear();
     var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
     week.push(fulldate);
  }
console.log(week);

Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.

You can use a third party date library to deal with dates. For example:

var startOfWeek = moment().startOf('week').toDate();
var endOfWeek   = moment().endOf('week').toDate();

EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)

Another popular alternative is date-fns.


_x000D_
_x000D_
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));
  }
  
 console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) )  // Mon Nov 08 2010
_x000D_
_x000D_
_x000D_


This works across year and month changes.

Date.prototype.GetFirstDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay())));
}

Date.prototype.GetLastDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());