Skip to content

JavaScript Date minus 1 day

  • by

You can use the getTime() method or the setDate() method to Date minus 1 day in JavaScript. Both approaches allow you to work with dates and times in JavaScript.

JavaScript Date minus 1-day example

A simple example code modifies the Date object and obtains the previous day’s date and time.

<!DOCTYPE html>
<html>
<body>
<script>
    const today = new Date();
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);

    console.log(yesterday)

</script>
</body>
</html>

Output:

JavaScript Date minus 1 day

Alternatively, you can use the setDate() method to modify the Date object in place:

const today = new Date();
today.setDate(today.getDate() - 1);

How to subtract days from a plain Date?

Answer: To subtract days from a plain Date object in JavaScript, you can use the setDate() and getDate() methods to modify the day of the month. Here’s an example:

const date = new Date('2023-03-28'); // create a new date object for March 28, 2023
const daysToSubtract = 7; // subtract 7 days
date.setDate(date.getDate() - daysToSubtract); // modify the date object to subtract 7 days

console.log(date); // output: Tue Mar 21 2023 00:00:00 GMT-0700 (Pacific Daylight Time)

Do comment if you have any doubts or suggestions on this Js date topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading