Open In App

Moment.js moment().toArray() Method

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

The moment().toArray() method is used to return an array that is similar to the parameters of a new Date() object. The array contains the values for the year, month, day, hours, minutes, seconds, and milliseconds.

Syntax:

moment().toArray();

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

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

Example 1:

Javascript




const moment = require('moment');
  
let momentOne = moment();
console.log(
    "MomentOne toArray():", momentOne.toArray()
)
  
let momentTwo = moment("01-08-2022", "MM-DD-YYYY");
console.log(
    "MomentTwo toArray():", momentTwo.toArray()
)
  
let momentThree = moment("10:25:20", "hh:mm:ss");
console.log(
    "MomentThree toArray():", momentThree.toArray()
)


Output:

MomentOne toArray(): [
  2022,  5, 28,
    23, 34, 58,
   562
]
MomentTwo toArray(): [
  2022, 0, 8, 0,
     0, 0, 0
]
MomentThree toArray(): [
  2022,  5, 28,
    10, 25, 20,
     0
]

Example 2:

Javascript




const moment = require('moment');
  
let moment1 = moment().year(2021);
console.log(
    "Moment1 toArray():", moment1.toArray()
)
  
let moment2 = moment1.add(10, 'months');
console.log(
    "Moment2 toArray():", moment2.toArray()
)
  
let moment3 = moment2.add(20, 'days');
console.log(
    "Moment3 toArray():", moment3.toArray()
)


Output:

Moment1 toArray(): [
  2021,  5, 28,
    23, 34, 58,
   577
]
Moment2 toArray(): [
  2022,  3, 28,
    23, 34, 58,
   577
]
Moment3 toArray(): [
  2022,  4, 18,
    23, 34, 58,
   577
]

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads