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

Solution 1:

var curr = new Date; // 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)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"

This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.

Making it work with first and last days in different months is left as an exercise for the user

Solution 2:

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.

Solution 3:

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..

Solution 4:

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

Solution 5:

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