Add Minutes to Date

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to add minutes to a given date in JavaScript. The addMinutesToDate function uses the Date constructor and various Date methods to create a new date object with a specified number of minutes added to it. This lab will help you understand how to manipulate dates in JavaScript and provide a useful utility function for your future 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`") subgraph Lab Skills javascript/variables -.-> lab-28126{{"`Add Minutes to Date`"}} javascript/data_types -.-> lab-28126{{"`Add Minutes to Date`"}} javascript/arith_ops -.-> lab-28126{{"`Add Minutes to Date`"}} javascript/comp_ops -.-> lab-28126{{"`Add Minutes to Date`"}} end

Function to Add Minutes to Date

To add a specific number of minutes to a given date, use the following function:

const addMinutesToDate = (date, n) => {
  // Create a Date object from the given date
  const d = new Date(date);
  // Add n minutes to the Date object
  d.setTime(d.getTime() + n * 60000);
  // Return a string representation of the new date in yyyy-mm-dd HH:MM:SS format
  return d.toISOString().split(".")[0].replace("T", " ");
};

To use this function, pass a string representation of the date as the first argument and the number of minutes to add (or subtract, if negative) as the second argument. For example:

addMinutesToDate("2020-10-19 12:00:00", 10); // '2020-10-19 12:10:00'
addMinutesToDate("2020-10-19", -10); // '2020-10-18 23:50:00'

Note that the function returns the new date as a string in yyyy-mm-dd HH:MM:SS format.

Summary

Congratulations! You have completed the Add Minutes to Date lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like