Open In App

Moment.js moment.duration().hours() Method

Last Updated : 23 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().duration().hours() method is used to get the hours of the duration. This number of hours is calculated as a subset of a day, therefore having a value between 0 and 23.

Syntax:

moment().duration().hours();

Parameters: This method does not accept any parameters.

Return Value: This method returns the hours (0-23) of the duration.

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

Example 1:

Javascript




const moment = require('moment');
  
let durationOne = moment.duration(20, 'hours');
let durationTwo = moment.duration(28, 'hours');
  
// This returns 20 as the number of
// hours is less than a whole day
console.log(
    "durationOne hours is:", durationOne.hours()
)
  
// This returns 4 as the number of hours
// is greater than a whole day (24 hours),
// and therefore returns the value of hours
// of the next day (next 4 hours)
console.log(
    "durationTwo hours is:", durationTwo.hours()
)


Output:

durationOne hours is: 20
durationTwo hours is: 4

Example 2: This example will help to understand the difference of this method with asHours() for a better understanding.

Javascript




let durationA = moment.duration(50, 'hours');
let durationB = moment.duration(64, 'hours');
  
// The asHours() method will return the
// length of the duration in hours
console.log(
    "Length of durationA in hours is:", durationA.asHours()
)
  
// The hours() method will return the hour of the duration
console.log("durationA hours is:", durationA.hours())
  
console.log(
    "Length of durationB in hours is:", durationB.asHours(
))
console.log("durationB hours is:", durationB.hours())


Output:

Length of durationA in hours is: 50
durationA hours is: 2
Length of durationB in hours is: 64
durationB hours is: 16

Reference: https://momentjs.com/docs/#/durations/hours/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads