How to use getTime() Method In Javascript
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 shows the use of the above-explained approach.
// 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 in 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
How to Add Days to Date in JavaScript?
You will learn how to add days to a date in JavaScript. We’ll focus on adding days to the current date. There are two methods to achieve this with the Date object:
Table of Content
- Using setDate() Method
- Using getTime() Method
Contact Us