What is the hour() method of moment.js?

Overview

With the moment.js package, we can manipulate the display of dates and times. The hour() method is used to get or set the hour of a specific time.

Syntax

// get hour
moment(time).hour()
// set hour
moment(time).hour(number)
The hour() method in moment.js

Parameters

time: This is the time whose hour we want to get or set.

number: This is the number we want to add to the hour if we want to set it. It can only be from 0 to 23.

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})
console.log("before setting hour")
// get the hour of the time
console.log(time1.hour()) // 10
console.log(time2.hour()) // 15
console.log(time3.hour()) // 16
console.log(time4.hour()) // 20
// set hour
time1.hour(23)
time2.hour(2)
time3.hour(12)
time4.hour(4)
console.log("After setting hour")
// get the hour of the time again
console.log(time1.hour()) // 10
console.log(time2.hour()) // 15
console.log(time3.hour()) // 16
console.log(time4.hour()) // 20

Explanation

  • Line 2: We require the moment package.
  • Lines 5–8: We create some time using the moment package.
  • Lines 12–15: We use the hour() method to get the hour of the times we created. Then, we print it to the console.
  • Lines 18–21: We use the hour() method again to modify the times we created by resetting their hours.

Free Resources