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.
functiongetStartOfWeek(date) {
// Copy date if provided, or use current date if not
date = date? newDate(+date) : newDate();
date.setHours(0,0,0,0);
// Set date to previous Sunday
date.setDate(date.getDate() - date.getDay());
return date;
}
functiongetEndOfWeek(date) {
date = getStartOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
document.write(getStartOfWeek());
document.write('<br>' + getEndOfWeek())
document.write('<br>' + getStartOfWeek(newDate(2016,2,27)))
document.write('<br>' + getEndOfWeek(newDate(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 =newDate();
day= currDate.getDay();
first_day =newDate(currDate.getTime() -60*60*24*day*1000);
last_day =newDate(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?"