The Wayback Machine - https://web.archive.org/web/20240621091936/https://www.geeksforgeeks.org/how-to-get-last-weeks-date-using-javascript/
Open In App

How to Get Last Week’s Date using JavaScript ?

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about how to get last week’s Date by using JavaScriptthe. JavaScript’s dynamic nature improves websites by adding dynamic elements. Fetching the previous week’s date is vital for event schedules, calendars, and timely data display.

There are several methods that can be used to get the last week’s Date using JavaScript, which is listed below:

  • Leveraging the Date Objects
  • Using se­tUTCDate Method

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using the Date Objects

The JavaScript Date­ object offers a variety of me­thods that simplify date operations. To retrie­ve the date from the previous week, one can subtract 7 days’ worth of milliseconds from the current date­ and elegantly display it on the scre­en.

Syntax:

const lastWeekDate = new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);

Example: The provide­d HTML code is responsible for cre­ating a web page that prominently showcase­s the text “Gee­ksforgeeks” as its main heading. To e­nsure an organized layout with cente­red content, CSS styling technique­s are employed, comple­mented by a background color. A visually appealing box is also include­d to highlight the “Last Week’s Date­,” which is dynamically calculated and displayed using JavaScript within this designate­d space.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, 
                   initial-scale=1.0">
    <title>Last Week's Date</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
  
        #dateContainer {
            background-color: #ffffff;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
            width: 300px;
            height: 150px;
            text-align: center;
        }
  
        .heading {
            color: green;
            font-size: 26px;
            border-bottom: 3px solid green;
            border-radius: 15px;
            padding: 10px;
            text-align: center;
        }
  
        .subheading {
            font-size: 20px;
        }
    </style>
</head>
  
<body>
    <div id="dateContainer">
        <h1 class="heading">
            Geeksforgeeks
        </h1>
        <h2 class="subheading">
            Last Week's Date:
        </h2>
        <p id="lastWeekDate"></p>
    </div>
  
    <script>
        // Get last week's date using Date object
        const currentDate = new Date();
        const lastWeekDate = new Date(currentDate.getTime()
            - 7 * 24 * 60 * 60 * 1000);
  
        // Display last week's date on the screen
        const lastWeekDateElement = 
            document.getElementById("lastWeekDate");
        lastWeekDateElement.textContent = 
              lastWeekDate.toDateString();
    </script>
</body>
  
</html>


Output:

last-week's-Date-using-javascript

Approach 2: Using se­tUTCDate Method

In this approach, we will use the `se­tUTCDate` method, this approach calculates the­ date of the previous we­ek by subtracting 7 days directly from the curre­nt date. Subsequently, it formats the­ result as “YYYY-MM-DD“. The JavaScript `Date` obje­ct is effectively e­mployed to manipulate dates and provide­s an alternative means of obtaining last we­ek’s date.

Syntax:

currentDate.setUTCDate(currentDate.getUTCDate() - 7);

Example: This HTML code is use­d to create a webpage­ with the title “Last Wee­k’s Date.” By utilizing CSS, the layout is structured ne­atly with centered conte­nt and a green-the­med design. The we­b page showcases the title­ “Geeksforgee­ks,” followed by “Last Week’s Date­:” along with the date from one we­ek ago. All of this is presente­d within a container that features subtle­ shadow effects.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Last Week's Date</title>
  
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
  
        #dateContainer {
            background-color: #ffffff;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
            width: 300px;
            height: 150px;
            text-align: center;
        }
  
        .heading {
            color: green;
            font-size: 26px;
            border-bottom: 3px solid green;
            border-radius: 15px;
            padding: 10px;
            text-align: center;
        }
  
        .subheading {
            font-size: 20px;
        }
    </style>
</head>
  
<body>
    <div id="dateContainer">
        <h1 class="heading">
            Geeksforgeeks
        </h1>
        <h2 class="subheading">
            Last Week's Date:
        </h2>
        <p id="lastWeekDate"></p>
    </div>
  
    <script>
  
        // Get last week's date using JavaScript
        const currentDate = new Date();
        currentDate.setUTCDate(currentDate.getUTCDate() - 7);
  
        // Format the date as "YYYY-MM-DD"
        const formattedDate = 
            `${currentDate.getUTCFullYear()} - 
            ${(currentDate.getUTCMonth() + 1)
                .toString().padStart(2, '0')
            } - ${currentDate.getUTCDate()
                .toString().padStart(2, '0')}`;
  
        // Display last week's date on the screen
        const lastWeekDateElement =
            document.getElementById("lastWeekDate");
        lastWeekDateElement.textContent = formattedDate;
    </script>
</body>
  
</html>


Output:

last-week's-Date-using-javascript-Example-2

Get last week’s Date using JavaScript Example 2



Similar Reads

How to validate if input date (end date) in input field must be after a given date (start date) using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type a date that must come after some given date(Ex. 'end date' must be after 'start date')
5 min read
How to validate if input date (start date) in input field must be before a given date (end date) using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type a date that must come before some given date (Ex: 'start date' must come before 'end da
5 min read
How to get the first and last date of current month using JavaScript ?
Given a month and the task is to determine the first and last day of that month in proper format using JavaScript. JavaScript getDate() Method: This method returns the day of the month (from 1 to 31) for the defined date. Syntax: Date.getDate() Parameters: This method does not accept any parameters. Return value: It returns a number from 1 to 31, r
3 min read
Moment.js Customize First Day of Week and First Week of Year
Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. In the calendar, we can use Moment.js to customize the First Day of the Week and the First Week of the Year as per our requirements. We will be using the moment.updateLocale() method for this customization. Syntax: moment.updateLocale('en', { week :
2 min read
How to get last day of a month from date in PHP ?
Given a date and the task is to print the last day of the month. We will use date() and strtotime() function to get the last day of the month. Used PHP functions: date() function: Format a local time/date. strtotime() function: Parse about any English textual datetime description into a Unix timestamp. Examples: Input: 2020-04-23 Output: Thursday I
2 min read
How to check the input date is equal to today's date or not using JavaScript ?
Given a date object and the task is to determine whether the given date is the same as today's date or not with the help of JavaScript. There are two well-famous approaches are discussed here. Approach 1: Get the input date from user (var inpDate) and the today's date by new Date(). Now, use .setHours() method on both dates by passing parameters of
3 min read
How to convert UTC date time into local date time using JavaScript ?
Given an UTC date and the task is to convert UTC date time into local date-time using JavaScript toLocaleString() function. Syntax: var theDate = new Date(Date.parse('DATE_IN_UTC')) theDate.toLocaleString() Example 1: This example converts UTC date time into local date time using JavaScript. C/C++ Code &lt;body&gt; &lt;h1 style=&quot;color:green;
1 min read
How to get first day of week in PHP?
Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string. Syntax: strtotime($EnglishDateTime, $ti
4 min read
How to get the Day of the Week in jQuery ?
The Date() constructor will not give the day of the week directly. It returns a number for the weekdays starting from 0 to 6. You need to implement some extra methods in jQuery to get the day of the week as listed below: Table of Content Using Date.getDay() methodUsing moment.jsUsing Date.getDay() methodIn this approach, we will use the Date.getDay
2 min read
How to get the Last Nested Property Using JavaScript ?
The last nested property in JavaScript is the innermost property within a hierarchy of nested objects, which can be accessed by traversing through the object. These are the following ways to get the last nested property using JavaScript: Table of Content Using recursionUsing Array.is() methodMethod 1: Using recursionThe code iterates through each p
2 min read