Calculating Days Ago with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will dive into JavaScript programming and create a function called daysAgo. This function takes a number as input and calculates the date that is n days ago from today. We will use the Date constructor, along with various methods such as Math.abs() and Date.prototype.setDate(), to accomplish this task and return the result as a string in yyyy-mm-dd format. By the end of this lab, you will have gained a deeper understanding of working with dates in JavaScript.


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-28253{{"`Calculating Days Ago with JavaScript`"}} javascript/data_types -.-> lab-28253{{"`Calculating Days Ago with JavaScript`"}} javascript/arith_ops -.-> lab-28253{{"`Calculating Days Ago with JavaScript`"}} javascript/comp_ops -.-> lab-28253{{"`Calculating Days Ago with JavaScript`"}} javascript/cond_stmts -.-> lab-28253{{"`Calculating Days Ago with JavaScript`"}} end

JavaScript function to Calculate Days Ago

Here's a JavaScript function that calculates the date of n days ago from today and returns it as a string in yyyy-mm-dd format:

const daysAgo = (n) => {
  const today = new Date();
  const daysAgoDate = new Date(today.setDate(today.getDate() - Math.abs(n)));
  return daysAgoDate.toISOString().split("T")[0];
};

Here's how it works:

  • The Date constructor is used to get the current date.
  • The Math.abs() function is used to ensure that the number of days is positive.
  • The Date.prototype.getDate() function is used to get the day of the month for the current date.
  • The Date.prototype.setDate() function is used to update the date accordingly.
  • The resulting date is returned as a string in yyyy-mm-dd format using the Date.prototype.toISOString() function.

Example usage:

daysAgo(20); // "2020-09-16" (if current date is 2020-10-06)

Summary

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

Other JavaScript Tutorials you may like