×

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be:

  • To find the duration, of course, someone is pursuing
  • To find the age of a user from his birth-date
  • Date customizations etc.

However, doing these calculations with the dates and time using JavaScript can become quite challenging, specifically if the database is huge. Therefore, here moment.js comes into the picture.

What is moment.js?

Moment.js is a JavaScript library.  Ithelps in validating, manipulating, parsing and displaying date/time in JavaScript in a simple manner. This library allows displaying of date as per localization and in human readable format. Moment.js can be used directly inside any browser.

Wherever the user wishes to use this library, the following code should be included within the script tag:

<script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>

Example:

To display the current date:

<html>
   <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>
   <body>
      <div style = "font-size:20px; color: red; " id = "currentdate"></div>
      <script type = "text/JavaScript">
         var val = moment().toString();
         document.getElementById("currentdate").innerHTML = val;
      </script>
   </body>
</html>

Output:

JavaScript Moment Date Difference

How are date-differences/durations calculated in JavaScript?

The following functions are used to find date-differences:

  • moment.duration().asMilliseconds();
    It is used to return the difference in dates or value in milliseconds.
  • moment.duration().asSeconds();
    It is used to return the difference in dates or value in seconds.
  • moment.duration().asMinutes();
    It is used to return the difference in dates or value in minutes.
  • moment.duration().asHours();
    It is used to return the difference in dates or value in hours.
  • moment.duration().asDays();
    It is used to return the difference in dates or value in days.
  • moment.duration().asWeeks();
    It is used to return the difference in dates or value in weeks.
  • moment.duration().asYears();
    It is used to return the difference in dates or value in years.

Syntax:

var duration = moment.duration(x.diff(y))

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in days</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var a = moment("2013-11-4"); //first date
var b = moment("2015-12-1"); // second date
var duration = moment.duration(b.diff(a)); // b-a
var days = duration.asDays();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + days+ " days";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in days

The difference between the dates is: 757 days

  • Finding the difference between current date and given date:
    • Date difference in seconds

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in seconds</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var now = moment(new Date()); //todays date(2021-9-11)
var end = moment("2021-2-6"); // another date
var duration = moment.duration(now.diff(end));
var val = duration.asSeconds();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " seconds";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in seconds

The difference between the dates is: 18831774.866 seconds

  • Date difference in days

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in days</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var now = moment(new Date()); //todays date(2021-9-11)
var end = moment("2021-2-6"); // another date
var duration = moment.duration(now.diff(end));
var val = duration.asDays();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " days";


    </script>


</html>

Output:                                                                   

The following example demonstrates the working of moment.js

Getting Difference between two dates in days

The difference between the dates is: 217.96392319444445 days

  • Date difference in months

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in months</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var now = moment(new Date()); //todays date(2021-9-11)
var end = moment("2021-2-6"); // another date
var duration = moment.duration(now.diff(end));
var val = duration.asMonths();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " months";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in months

The difference between the dates is: 7.161205484864318 months

  • Date difference in years

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in years</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var now = moment(new Date()); //todays date(2021-9-11)
var end = moment("2018-12-16"); // another date
var duration = moment.duration(now.diff(end));
var val = duration.asYears();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " years";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in years

The difference between the dates is: 2.740550074861476 years

  • Finding the difference between two given dates:
    • Date difference in seconds

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in seconds</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var a = moment("2013-11-4"); //first date
var b = moment("2015-12-1"); // second date
var duration = moment.duration(b.diff(a)); // b-a
var val = duration.asSeconds();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " seconds";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in seconds

The difference between the dates is: 65404800 seconds

  • Date difference in weeks

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in days</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var a = moment("2013-11-4"); //first date
var b = moment("2015-12-1"); // second date
var duration = moment.duration(b.diff(a)); // b-a
var val = duration.asWeeks();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " weeks";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in days

The difference between the dates is: 108.14285714285714 weeks

  • Date difference in months

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in months</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var a = moment("2013-11-4"); //first date
var b = moment("2015-12-1"); // second date
var duration = moment.duration(b.diff(a)); // b-a
var val = duration.asMonths();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " months";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in months

The difference between the dates is: 24.871147251483603 months

  • Date difference in years

Example:

<!DOCTYPE html>
<html>
     <head>
      <title>MomentJS Example</title>
      <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
     
   </head>


  <body>
    <h2>The following is an example to demonstrate the working of moment.js</h2>
    <br>
    <p>Getting Difference between two dates in years</p>
    <br>
    <p id="tcontent"></p>
  </body>
  <script>
    console.clear();
var a = moment("2013-11-4"); //first date
var b = moment("2015-12-1"); // second date
var duration = moment.duration(b.diff(a)); // b-a
var val = duration.asYears();


  document.getElementById("tcontent").innerHTML = "The difference between the dates is: " + val+ " years";


    </script>


</html>

Output:

The following example demonstrates the working of moment.js

Getting Difference between two dates in years

The difference between the dates is: 2.0725956042903 years


Related Topics

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 minutes read.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.