Home  >  Article  >  Web Front-end  >  How to Determine the First and Last Days of the Current Week in JavaScript?

How to Determine the First and Last Days of the Current Week in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 08:57:01841browse

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

  1. Create a new Date object representing the current date: var curr = new Date();
  2. Calculate the first day of the week: var first = curr.getDate() - curr.getDay();
  3. Calculate the last day of the week: var last = first 6;
  4. Use toUTCString() to convert the dates to a string: var firstday = new Date(curr.setDate(first)).toUTCString(); and var lastday = new Date(curr.setDate(last)).toUTCString();

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn