Open In App

Moment.js moment().toObject() Method

Last Updated : 12 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().toObject() method is used to return the Moment object as a JavaScript object with the date parameters in the properties.

Syntax:

moment().toObject();

Parameters: This method does not accept any parameters:

Return Value: This method returns the duration as a JavaScript Object.

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

Example 1:

Javascript




const moment = require('moment');
  
let momentOne = moment();
let momentTwo = moment()
                .add(15, 'months')
                .add(10, 'days')
                .add(24, 'seconds');
  
console.log(
    "Object form of momentOne is:",
    momentOne.toObject()
)
console.log(
    "Object form of momentTwo is:",
    momentTwo.toObject()
)


Output:

Object form of momentOne is: {
  years: 2022,
  months: 6,
  date: 10,
  hours: 23,
  minutes: 36,
  seconds: 3,
  milliseconds: 659
}
Object form of momentTwo is: {
  years: 2023,
  months: 9,
  date: 20,
  hours: 23,
  minutes: 36,
  seconds: 27,
  milliseconds: 659
}

Example 2:

Javascript




const moment = require('moment');
  
let momentA = moment(
    '25/12/2022', 'DD/MM/YYYY'
);
let momentB = moment({
    year: 2017, month: 5, day: 4,
    hour: 1, minute: 15, second: 30,
    millisecond: 100
});
  
console.log(
    "Object form of momentA is:",
    momentA.toObject()
)
console.log(
    "Object form of momentB is:",
    momentB.toObject()
)


Output:

Object form of momentA is: {
  years: 2022,
  months: 11,
  date: 25,
  hours: 0,
  minutes: 0,
  seconds: 0,
  milliseconds: 0
}
Object form of momentB is: {
  years: 2017,
  months: 5,
  date: 4,
  hours: 1,
  minutes: 15,
  seconds: 30,
  milliseconds: 100
}

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads