Open In App

Moment.js moment.duration().milliseconds() Method

Last Updated : 23 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().duration().milliseconds() method is used to get the number of milliseconds of the duration. This number of milliseconds is calculated as a subset of the a seconds, therefore having a value between 0 and 999. The length of a second is 1000 milliseconds.

Syntax:

moment().duration().milliseconds();

Parameters: This method does not accept any parameters.

Return Value: This method returns the milliseconds (0-999) of the duration.

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

The below examples will demonstrate the Moment.js moment.duration().milliseconds() Method.

Example 1:

Javascript




const moment = require('moment');
  
let durationOne =
    moment.duration(900, 'milliseconds');
let durationTwo = 
    moment.duration(5750, 'milliseconds');
  
// This returns 900 as the number of
// milliseconds is less than a whole second
console.log(
    "durationOne milliseconds is:",
    durationOne.milliseconds()
)
  
// This returns 750 as the number of milliseconds
// is greater than 5 seconds, and therefore
// returns the value of milliseconds
// of the next second (next 750 milliseconds)
console.log(
    "durationTwo milliseconds is:",
    durationTwo.milliseconds()
)


Output:

durationOne milliseconds is: 900
durationTwo milliseconds is: 750

Example 2: This example will help to understand the difference of this method with asMilliseconds() for a better understanding.

Javascript




const moment = require('moment');
  
let durationA =
    moment.duration(1, 'seconds');
let durationB = 
    moment.duration({ seconds: 5, milliseconds: 250 });
  
// The asMilliseconds() method will return the
// length of the duration in milliseconds
console.log(
    "Length of durationA in milliseconds is:",
    durationA.asMilliseconds()
)
console.log(
    "durationA milliseconds is:",
    durationA.milliseconds()
)
  
console.log(
    "Length of durationB in milliseconds is:",
    durationB.asMilliseconds()
)
  
console.log(
    "durationB milliseconds is:",
    durationB.milliseconds()
)


Output:

Length of durationA in milliseconds is: 1000
durationA milliseconds is: 0
Length of durationB in milliseconds is: 5250
durationB milliseconds is: 250

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads