Date Difference in Minutes

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 difference between two dates in minutes using JavaScript. We will use the Date object and a simple mathematical formula to obtain the time difference. By the end of this lab, you will be able to implement this functionality into your own projects and applications.


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-28237{{"`Date Difference in Minutes`"}} javascript/data_types -.-> lab-28237{{"`Date Difference in Minutes`"}} javascript/arith_ops -.-> lab-28237{{"`Date Difference in Minutes`"}} javascript/comp_ops -.-> lab-28237{{"`Date Difference in Minutes`"}} end

Function to Calculate Date Difference in Minutes

To calculate the difference (in minutes) between two dates, use the following function:

const getMinutesDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 60);

Simply subtract the two Date objects and divide by the number of milliseconds in a minute to get the difference (in minutes) between them.

Here's an example usage of the function:

getMinutesDiffBetweenDates(
  new Date("2021-04-24 01:00:15"),
  new Date("2021-04-24 02:00:15")
); // 60

To start practicing coding, open the Terminal/SSH and type node.

Summary

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

Other JavaScript Tutorials you may like