The Wayback Machine - https://web.archive.org/web/20230403084022/https://www.geeksforgeeks.org/moment-js-moment-diff-function/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Moment.js moment().diff() Function

Improve Article
Save Article
Like Article
  • Last Updated : 20 Mar, 2023
Improve Article
Save Article
Like Article

The moment().diff() function is used to get the difference in milliseconds of given dates which are passed as parameters to this function. 

Syntax:

moment().diff(Moment|String|Number|Date|Array, String, Boolean);

Parameters: This function has two parameters, first one is the date of type Moment|String|Number|Date|Array, and the second parameter is an optional parameter of the boolean type which is used to get floating numbers as a result instead of integers. 

Return Value: This function returns the date in milliseconds.

 Installation of moment module:

You can visit the link to Install moment module. You can install this package by using this command.

npm install moment

After installing the moment module, you can check your moment version in the command prompt using the command.

npm version moment

Project Structure:

After that, you can just create a folder and add a file, for example, index.js as shown below.

Example 1: Filename: index.js 

javascript




// Requiring the module
const moment = require('moment');
 
let dateOne = moment([2019, 03, 17]);
let dateTwo = moment([2001, 10, 28]);
 
// Function call
let result = dateOne.diff(dateTwo, 'days')
 
console.log("No of Days:", result)

Steps to run the program:

Run the index.js file using the below command:

node index.js

Output:

No of Days: 6349

Example 2: Filename: index.js 

javascript




// Requiring the module
const moment = require('moment');
  
function getYearDiff(dateOne, dateTwo) {
   return dateOne.diff(dateTwo, 'years', true);
}
  
// Function call
let result = getYearDiff(moment([2019, 11,
    30]), moment([2001, 2, 17]));
 
console.log("No of years difference:", result)

Steps to run the program:

Run the index.js file using the below command:

node index.js

Output:

No of years difference: 18.78611111111111

Reference: https://momentjs.com/docs/#/displaying/difference/


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!