Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-19 08:57:01
Original
841 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!