Moment.js moment().diff() Function
Last Updated :
12 Apr, 2025
The moment().diff() function is used to calculate the difference between two dates using Moment.js. By default, it returns the difference in milliseconds, but you can also specify a different unit (e.g., days, years) for the result.
Syntax:
moment().diff(Moment|String|Number|Date|Array, [String], [Boolean]);
Parameters:
- Moment|String|Number|Date|Array: The date to compare with the current moment.
- String (optional): The unit of time (e.g., 'days', 'months', 'years').
- Boolean (optional) :If true, returns a floating point number instead of an integer.
Return Value: This function returns the date in milliseconds.
The moment().diff()
function calculates the difference between two dates in Moment.js.
Steps to create the application:
Step 1: You can install this package by using this command.
npm install express
Step 2: After installing the express module, you can check your express version in the command prompt using the command.
npm version express
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^5.1.0",
}
Example 1: Below is the code example of moment().diff() Function
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:
node index.js
Output:
No of Days: 6349
Example 2: Below is the code example of moment().diff() Function
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:
node index.js
Output:
No of years difference: 18.78611111111111
Conclusion
Moment.js is still widely used, but it's now in maintenance mode and not recommended for new projects. Consider using modern alternatives like Luxon, date-fns, or Day.js for better performance and up-to-date features.