JavaScript getHours()

getHours() returns the hours component of a JavaScript Date according to local time. The normal range is 0 to 23.

const now = new Date();
const value = now.getHours();
console.log(value);

getHours() Syntax and Return Value Top ↑

const value = date.getHours();

The method takes no parameters. If the Date is invalid, it returns NaN.

Pad Hours to Two Digits Top ↑

const value = String(date.getHours()).padStart(2, "0");

Using getHours() in a Clock Top ↑

const now = new Date();
const hh = String(now.getHours()).padStart(2, "0");
const mm = String(now.getMinutes()).padStart(2, "0");
const ss = String(now.getSeconds()).padStart(2, "0");
console.log(`${{hh}}:${{mm}}:${{ss}}`);

For an updating display, see the JavaScript clock and timer tutorial.

getHours() and Its UTC Equivalent Top ↑

const localValue = date.getHours();
const utcValue = date.getUTCHours();

Use the local method for the host's local time and the UTC method when your logic is explicitly based on UTC. See UTC date methods.

Invalid Dates Top ↑

const bad = new Date("invalid");
console.log(bad.getHours()); // NaN

Convert 24-Hour Time to 12-Hour Time Top ↑

const hour24 = date.getHours();
const period = hour24 >= 12 ? "PM" : "AM";
const hour12 = hour24 % 12 || 12;

Common getHours() Mistakes Top ↑

  • Assuming the returned number is already zero-padded for display.
  • Mixing local and UTC components in the same calculation.
  • Ignoring invalid Date values.
  • Using raw numeric components when locale-aware formatting would better serve users.

Date Reference Next Date Method




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer