Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

The moment().duration().toISOString() Method is used to get an ISO8601 standard formatted string of the given duration. The UTC mode is used for the timestamp regardless of the locale of the moment, so that consistency can be maintained with the native Date API of JavaScript. This behaviour can be disabled by passing true to the keepOffset parameter.

Note: The library will try to use the native Date toISOString() method for better performance.

Syntax:

moment().duration().toISOString(keepOffset);

Parameters: This method accepts a single parameter as mentioned above and described below:

  • keepOffset: This parameter is used to specify whether UTC conversion is enabled or not. It is an optional parameter.

Return Value: This method returns the duration as the ISO String format.

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().toISOString() Method.

Example 1:

Javascript




const moment = require('moment');
  
let durationOne = moment.duration(9, 'months');
let durationTwo = moment.duration(19, 'months');
let durationThree = moment.duration(10, 'weeks');
  
console.log(
  "ISOString of durationOne is:",
  durationOne.toISOString()
)
console.log(
  "ISOString of durationTwo is:",
  durationTwo.toISOString()
)
console.log(
  "ISOString of durationThree is:",
  durationThree.toISOString()
)


Output:

ISOString of durationOne is: P9M
ISOString of durationTwo is: P1Y7M    
ISOString of durationThree is: P70D

Example 2:

Javascript




const moment = require('moment');
  
let durationA = moment.duration(
  {months: 4, days: 5, hours: 9, seconds: 23}
);
let durationB = moment.duration(
  {hours: 3, minutes: 36, seconds: 6}
);
let durationC = moment.duration(
  {years: 2, months: 6, days: 9}
);
  
console.log(
  "ISOString of durationA is:",
  durationA.toISOString()
)
console.log(
  "ISOString of durationB is:",
  durationB.toISOString()
)
console.log(
  "ISOString of durationC is:",
  durationC.toISOString()
)


Output:

ISOString of durationA is: P4M5DT9H23S
ISOString of durationB is: PT3H36M6S  
ISOString of durationC is: P2Y6M9D

Reference: https://momentjs.com/docs/#/displaying/as-iso-string/



Last Updated : 15 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads