Determining the first and last days of the current week can be a common task when working with date-related data. In JavaScript, there are a few methods that can be utilized to achieve this.
One approach involves creating a new Date object and utilizing its getDate() and getDay() methods. The getDate() method returns the day of the current month while getDay() returns the day of the week (0 for Sunday, 6 for Saturday). To obtain the first day of the current week, subtract the getDay() value from the getDate() value. Similarly, to find the last day of the week, add 6 to the first day.
For example, to get both variants with Sunday as the start day of the week, use the following code:
<code class="javascript">var curr = new Date(); // Get the 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(); console.log("First day:", firstday); console.log("Last day:", lastday);</code>
Output:
First day: Sun, 06 Mar 2022 00:00:00 GMT Last day: Sat, 12 Mar 2022 00:00:00 GMT
To modify this code for Monday as the start day of the week, simply subtract 1 from the first variable's calculation. Additionally, to handle cases where the first and last days of the week fall in different months, further adjustments may be required.
The above is the detailed content of How to Find First and Last Days of the Current Week in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!