Calculate Date n Days Ahead

Beginner

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

Introduction

In this lab, we will explore how to calculate the date of n days from today using JavaScript. We will use the Date constructor, along with various date methods such as getDate() and setDate(), to manipulate dates and return a string representation of the calculated date in yyyy-mm-dd format. By the end of this lab, you will have a better understanding of how to work with dates in JavaScript and be able to apply this knowledge to various projects.

Function to Calculate the Date of 'n' Days from Today

To calculate the date 'n' days from today, follow these steps:

  • Open the Terminal/SSH and type 'node' to start practicing coding.
  • Use the Date constructor to get the current date.
  • Use Math.abs() and Date.prototype.getDate() to update the date accordingly.
  • Set the result using Date.prototype.setDate().
  • Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.

Here's the code:

const daysFromNow = (n) => {
  let currentDate = new Date();
  currentDate.setDate(currentDate.getDate() + Math.abs(n));
  return currentDate.toISOString().split("T")[0];
};

Example usage:

daysFromNow(5); // Output: 2020-10-13 (if current date is 2020-10-08)

Summary

Congratulations! You have completed the Days From Now lab. You can practice more labs in LabEx to improve your skills.