Open In App

Moment.js moment().toJSON() Method

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

Syntax:



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

Parameters: This method does not accept any parameters:

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

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

Example 1:




const moment = require('moment');
  
// Example 1
let publishTime = moment();
  
let article = {
    title: "Article One",
    publishTime: publishTime.toJSON()
}
  
console.log(
    "Article Details:", JSON.stringify(article)
)

Output:

Article Details: {
    "title":"Article One",
    "publishTime":"2022-06-28T18:19:35.621Z"
}

Example 2:




const moment = require('moment');
  
let startTime = moment();
let endTime = startTime.add(15, 'minutes');
  
let timeCalculation = {
    startTime: startTime.toJSON(),
    endTime: endTime.toJSON()
}
  
console.log(
    "Duration:", JSON.stringify(timeCalculation)
)

Output:

Duration: {
    "startTime":"2022-06-28T18:34:35.630Z",
    "endTime":"2022-06-28T18:34:35.630Z"
}

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


Article Tags :