Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

moment.js
javascript

What is the moment().toObject() method in the moment.js library?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

If we want to return an object with the time and date manipulation library, moment.js, then we have to use the toObject() method. It returns an object which contains the year, month, day-of-month, hour, minute, seconds, and milliseconds of the date or time specified.

Syntax

time.toObject()
syntax for toObject() method in moment.js

Parameters

time: This is the time we want to return as an object that contains all its parts.

Return value

The value returned is an object.

Example

// require the moment module
const moment = require("moment")
// create some dates and time
const time1 = moment([2010, 1, 14, 10, 25, 50, 125])
const time2 = moment(new Date) // current date and time
const time3 = moment(1318781876406)
const time4 = moment({hour: 20, minute: 20, second: 34})
const time5 = moment([2022, 5, 17])
const time6 = moment([2025, 4, 18])
const time7 = moment().add(25, "seconds");
// get times and dates as objects
console.log(time1.toObject())
console.log(time2.toObject())
console.log(time3.toObject())
console.log(time4.toObject())
console.log(time5.toObject())
console.log(time6.toObject())
console.log(time7.toObject())
toObject() method in moment.js

Explanation

  • Line 2: We require the moment.js package.
  • Lines 5–11: We create some times and dates.
  • Lines 14–20: We use the toObject() method to return the object representation of the dates and times we created and print them to the console.

RELATED TAGS

moment.js
javascript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring