How to Obtain the Current Week's First and Last Days in JavaScript
Determining the first and last days of the current week is a common task in web development. JavaScript offers a simple solution using the Date object.
Getting First and Last Days with Sunday as the Week's Start
<code class="javascript">var curr = new Date(); // Current date object var first = curr.getDate() - curr.getDay(); // First day of the week var last = first + 6; // Last day of the week // Convert dates to UTC strings var firstday = new Date(curr.setDate(first)).toUTCString(); var lastday = new Date(curr.setDate(last)).toUTCString(); console.log('First Day (Sunday): ', firstday); console.log('Last Day (Saturday): ', lastday);</code>
Extending to Monday as the Week's Start
To start the week on Monday, simply subtract one day from the first day calculation:
<code class="javascript">first = first - 1;</code>
Handling Cross-Month Transitions
Determining the first and last days in different months requires additional logic. This exercise is left to the user to implement.
The above is the detailed content of How Do I Find the Current Week\'s First and Last Days in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!