×

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 Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 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 Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes 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.

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 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 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.

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.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes 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 redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 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.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes 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.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 minutes read.