Open In App

How to Add Days to Date in JavaScript?

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Adding days to a date in JavaScript is a common task when working with dates and times. This involves manipulating the Date object to calculate a future or past date by adding a specific number of days. This is useful for tasks like scheduling events, and deadlines, or simply adjusting dates dynamically within an application.

There are two methods to achieve this with the Date object:

1. Using setDate() Method

The setDate() method allows you to modify the day of the month for a Date object. To use this method, you start by creating a Date object that represents the current date. You can then add a specific number of days to this date and assign the result to a new Date object.

Example: This example we defines a function addDays to add a specified number of days to a date, then applies it to the current date, and logs the new date.

JavaScript
// Function to Add days to current date
function addDays(date, days) {
    const newDate = new Date(date);
    newDate.setDate(date.getDate() + days);
    return newDate;
}

// Get the current date
const todayDate = new Date();

// Number of days that we want to add to the current date
const days = 7;

// Function call to add days
const newDate = addDays(todayDate, days);

console.log("New Date: ", newDate.toDateString());

Output
New Date:  Sun Dec 17 2023

2. Using getTime() Method

The getTime() method in JavaScript returns the number of milliseconds elapsed since January 1, 1970. To add a specific number of days to a date, we first convert the days into milliseconds and then add them to the current date represented in milliseconds. This approach enables precise date manipulation in JavaScript.

Example: This example the addDays function adds a specified number of days to a given date. It calculates the new date and returns it, then logs the updated date using toDateString().

JavaScript
// Function to Add days to current date
function addDays(date, days) {
    const newDate = new Date(date.getTime() + days * 24 * 60 * 60 * 1000);
    return newDate;
}

// Get the current date
const todayDate = new Date();

// Number of days that we want to add to the current date
const days = 7;

// Function call to add days
const newDate = addDays(todayDate, days);

console.log("New Date:", newDate.toDateString());

Output
New Date:  Sun Dec 17 2023

Next Article

Similar Reads