Add Date by Days in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28123{{"`Add Date by Days in JavaScript`"}} javascript/data_types -.-> lab-28123{{"`Add Date by Days in JavaScript`"}} javascript/arith_ops -.-> lab-28123{{"`Add Date by Days in JavaScript`"}} javascript/comp_ops -.-> lab-28123{{"`Add Date by Days in JavaScript`"}} end

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.

Other JavaScript Tutorials you may like