Home > Article > Web Front-end > How to Calculate the First and Last Days of the Current Week in JavaScript?
Getting First and Last Days of the Current Week in JavaScript
When working with dates, it often becomes necessary to determine the first and last days of the current week. JavaScript provides convenient ways to achieve this, as demonstrated below:
Calculating the First and Last Day with Sunday as the Start:
To find the first and last days of the current week starting from Sunday, use the following code:
<code class="js">var curr = new Date(); var first = curr.getDate() - curr.getDay(); var last = first + 6; var firstday = new Date(curr.setDate(first)).toUTCString(); var lastday = new Date(curr.setDate(last)).toUTCString();</code>
This will calculate the first day as Sunday and the last day as Saturday of the current week.
Adapting for Monday as the Start:
To adjust the calculations for a Monday start, modify the following line:
<code class="js">var first = curr.getDate() - curr.getDay() + 1;</code>
This adds 1 to the calculated first day, ensuring it starts from Monday.
Handling Month Transitions:
As mentioned in the provided answer, handling cases where the first or last day of the week falls in a different month is an exercise left for the user. Here's a hint:
By following these steps, you can easily determine the first and last days of the current week, whether starting on Sunday or Monday.
The above is the detailed content of How to Calculate the First and Last Days of the Current Week in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!