Add Date by Days in JavaScript

Beginner

This tutorial is from open-source community. Access the source code

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 96% completion rate. It has received a 100% positive review rate from learners.

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Date constructor to create a Date object from the first argument.
  3. Use Date.prototype.getDate() and Date.prototype.setDate() to add n days to the given date.
  4. Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.

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.