Home >Web Front-end >JS Tutorial >How to Determine the First and Last Days of the Current Week in JavaScript?
Determining the Current Week's First and Last Days in JavaScript
In JavaScript, working with dates can occasionally be complex. Getting the first and last day of the current week is a particularly common task that can trip up developers. This article will explore two methods for accomplishing this task, with customizable options for Sunday or Monday as the start of the week.
Method 1: Using the Date Object
Example:
<code class="javascript">var curr = new Date(); var first = curr.getDate() - curr.getDay(); var last = first + 6; console.log(new Date(curr.setDate(first)).toUTCString()); // Output: "Sun, 06 Mar 2011 12:25:40 GMT" console.log(new Date(curr.setDate(last)).toUTCString()); // Output: "Sat, 12 Mar 2011 12:25:40 GMT"</code>
Method 2: Using Moment.js (Optional)
If you are using Moment.js, a popular date manipulation library, you can use the following code:
<code class="javascript">var curr = moment(); var first = curr.startOf('week').format('YYYY-MM-DD'); var last = curr.endOf('week').format('YYYY-MM-DD');</code>
The above is the detailed content of How to Determine the First and Last Days of the Current Week in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!