What is the moment().diff() method in moment.js?
Overview
Moment.js provides many methods and functions that enable one to manipulate and display dates according to their choice. With the diff() method, we can get the difference in milliseconds between two times.
Syntax
time1.diff(time2)
Syntax for diff() method in moment.js
Parameters
time1,time2: These are the times whose differences we want to get.
Return value
int: The value returned is an integer which is the millisecond betweentime1andtime2.
Example
// require the moment moduleconst moment = require("moment")// create some dates and timeconst time1 = moment([2010, 1, 14, 10, 25, 50, 125])const time2 = moment(new Date) // current date and timeconst time3 = moment(1318781876406)const time4 = moment({hour: 20, minute: 20, second: 34})const time5 = moment([2022, 5, 17])const time6 = moment([2025, 4, 18])const time7 = moment().add(25, "seconds");// get the difference between one time and anotherconsole.log(time1.diff(time2))console.log(time2.diff(time3))console.log(time3.diff(time4))console.log(time4.diff(time5))console.log(time5.diff(time6))console.log(time7.diff(time2))
Explanation
- Line 2: We require the
momentpackage. - Lines: 5–11: We create some dates and times.
- Lines 14–19: Using the
diff()method, we get the difference between the times and print them to the console.