Open In App

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

The moment().duration().toJSON() method is used to get the JSON format of the duration. During the serialization process, the ISO8601 format would be used for converting the duration into a format suitable for the JSON output.

Note: It would return an Invalid Date if the Duration itself is invalid.



Syntax:

moment().duration().toJSON();

Parameters: This method does not accept any parameters:



Return Value: This method returns the duration as a JSON 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

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




const moment = require('moment');
  
let readingTime = moment.duration(10, 'minutes');
let lastUpdated = moment.duration(-9, 'months');
  
let blogPost = {
    title: "Blog One",
    readingTime: readingTime.toJSON(),
    lastUpdated: lastUpdated.toJSON()
}
  
console.log(JSON.stringify(blogPost));

Output:

{
    "title": "Blog One",
    "readingTime": "PT10M",
    "lastUpdated": "-P9M"
}

Example 2:




const moment = require('moment');
  
let datetime = 
    moment.duration({months: 5, days: 2, hours: 4, seconds: 1});
let time = 
    moment.duration({hours: 5, minutes: 6, seconds: 55});
let date = 
    moment.duration({years: 10, months: 5, days: 10});
  
let exampleJSON = {
    durationA: datetime.toJSON(),
    durationB: time.toJSON(),
    durationC: date.toJSON()
}
  
console.log(JSON.stringify(exampleJSON));

Output:

{
    "durationA": "P5M2DT4H1S",
    "durationB": "PT5H6M55S",
    "durationC": "P10Y5M10D"
}

Reference: https://momentjs.com/docs/#/durations/as-json/


Article Tags :