Introduction
In this lab, we will explore how to add days to a given date in JavaScript. We will create a function that takes in a date and a number of days to add, and returns the resulting date in a string format. We will use the Date constructor and various Date methods to perform the date arithmetic and return the final date.
Function to Add Days to a Date
Here's a function that can calculate the date of n days from the given date and return its string representation.
To use the function, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Dateconstructor to create aDateobject from the first argument. - Use
Date.prototype.getDate()andDate.prototype.setDate()to addndays to the given date. - Use
Date.prototype.toISOString()to return a string inyyyy-mm-ddformat.
Here's the code for the function:
const addDaysToDate = (date, n) => {
const d = new Date(date);
d.setDate(d.getDate() + n);
return d.toISOString().split("T")[0];
};
You can test the function using the following examples:
addDaysToDate("2020-10-15", 10); // '2020-10-25'
addDaysToDate("2020-10-15", -10); // '2020-10-05'
Summary
Congratulations! You have completed the Add Days to Date lab. You can practice more labs in LabEx to improve your skills.