Calculate Date n Days Ahead

JavaScriptJavaScriptBeginner
Practice Now

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.


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`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") subgraph Lab Skills javascript/variables -.-> lab-28254{{"`Calculate Date n Days Ahead`"}} javascript/data_types -.-> lab-28254{{"`Calculate Date n Days Ahead`"}} javascript/arith_ops -.-> lab-28254{{"`Calculate Date n Days Ahead`"}} javascript/comp_ops -.-> lab-28254{{"`Calculate Date n Days Ahead`"}} javascript/cond_stmts -.-> lab-28254{{"`Calculate Date n Days Ahead`"}} end

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.

Other JavaScript Tutorials you may like