Open In App

Moment.js moment().get() Method

The moment().get() method is used to get the given unit of time from the Moment object as a String. The unit can be specified in all the recognized variations of the unit including its plural and short forms. It can be used to return the value of a year, month, date, hour, minute, and millisecond.

Syntax:



moment().get( unit );

Parameters: This method accepts a single parameter as mentioned above and described below:

Return Value: This method returns a string of the given unit of time from the Moment 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().get() Method.

Example 1:




const moment = require('moment');
  
let momentOne = moment();
console.log(
    "momentOne date:", momentOne.get('date')
)
console.log(
    "momentOne month:", momentOne.get('month')
)
console.log(
    "momentOne year:", momentOne.get('year')
)
  
let momentTwo = 
    moment()
        .clone()
        .add(8, 'days')
        .add(5, 'months');
console.log(
    "momentTwo date:", momentTwo.get('D')
)
console.log(
    "momentTwo month:", momentTwo.get('M')
)
console.log(
    "momentTwo year:", momentTwo.get('Y')
)

Output:

momentOne date: 11
momentOne month: 6       
momentOne year: 2022     
momentTwo date: 19       
momentTwo month: 11      
momentTwo year: 2022     

Example 2:




const moment = require('moment');
  
let momentA = moment();
console.log(
    "momentA hours:", momentA.get('hour')
)
console.log(
    "momentA minutes:", momentA.get('minute')
)
console.log(
    "momentA seconds:", momentA.get('second')
)
console.log(
    "momentA milliseconds:", momentA.get('millisecond')
)
  
let momentB = moment()
                .clone()
                .add(10, 'hours')
                .add(100, 'millisecond');
console.log(
    "momentB hours:", momentB.get('H')
)
console.log(
    "momentB minutes:", momentB.get('m')
)
console.log(
    "momentB seconds:", momentB.get('s')
)
console.log(
    "momentB milliseconds:", momentB.get('ms')
)

Output:

momentA hours: 1
momentA minutes: 54      
momentA seconds: 39      
momentA milliseconds: 237
momentB hours: 11
momentB minutes: 54
momentB seconds: 39
momentB milliseconds: 338

Reference: https://momentjs.com/docs/#/get-set/get/


Article Tags :