Skip to content Skip to sidebar Skip to footer

How To Get First And Last Day Of Current Week When Days Are In Different Months?

For example, in the case of 03/27/2016 to 04/02/2016, the dates fall in different months. var curr = new Date; // get current date var first = curr.getDate() - curr.getDay(); var l

Solution 1:

The getDay method returns the number of the day in the week, with Sunday as 0 and Saturday as 6. So if your week starts on Sunday, just subtract the current day number in days from the current date to get the start, and add 6 days get the end, e.g.

function getStartOfWeek(date) {
  
  // Copy date if provided, or use current date if not
  date = date? new Date(+date) : new Date();
  date.setHours(0,0,0,0);
  
  // Set date to previous Sunday
  date.setDate(date.getDate() - date.getDay());
  
  return date;
}

function getEndOfWeek(date) {
  date = getStartOfWeek(date);
  date.setDate(date.getDate() + 6);
  return date; 
}
  
document.write(getStartOfWeek());

document.write('<br>' + getEndOfWeek())

document.write('<br>' + getStartOfWeek(new Date(2016,2,27)))

document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))

Solution 2:

I like the moment library for this kind of thing:

moment().startOf("week").toDate();
moment().endOf("week").toDate();

Solution 3:

You can try this:

var currDate = new Date();
day = currDate.getDay();
first_day = new Date(currDate.getTime() - 60*60*24* day*1000); 
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000);

Post a Comment for "How To Get First And Last Day Of Current Week When Days Are In Different Months?"