×

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

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

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

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

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.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 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 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 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 dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

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 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 pursuingTo find the age of a user from...

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

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

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.