Moment.js moment.duration(x.diff(y)) Method

The moment().duration(x.diff(y)) method is used to create a duration using the difference between two Moment objects by using the diff() method.

Syntax:

moment().duration( x.diff(y) );

Parameters: This method accepts a single parameter that uses the diff() method to find the difference between two Moment objects.

Return Value: This method returns a duration that is the difference between two Moment objects.

Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

Example 1: This example will demonstrate the Moment.js moment().duration(x.diff(y)) Method.

Javascript




const moment = require('moment');
  
let momentOne = 
    moment("11-05-1985", "MM-DD-YYYY");
let momentTwo = 
    moment("11-14-1985", "MM-DD-YYYY");
  
let durationA = 
    moment.duration(momentOne.diff(momentTwo));
console.log(durationA.humanize())


Output:

9 days

Example 2:

Javascript




let startTime = moment();
let endTime = 
    startTime.clone().add(35, 'seconds');
let cleanTime = 
    endTime.clone().add(5, 'minutes');
  
let timerDuration = 
    moment.duration(endTime.diff(startTime));
console.log(timerDuration.humanize())
  
let timerDuration2 = 
    moment.duration(cleanTime.diff(startTime));
console.log(timerDuration2.humanize())


Output:

a few seconds
6 minutes

Reference: https://momentjs.com/docs/#/durations/diffing/



Contact Us