How to Get Hours and Minutes From a Date in JavaScript

To get the hours and minutes from a Date object in JavaScript, use the “Date Object’s getHours() and getMinutes() methods.” These methods return the date’s hour (0-23) and minute (0-59) components, respectively.

Syntax

getHours();

getMinutes();

Return value

A string representing the time.

Visual representation

Get Hours and Minutes From a Date in JavaScript

Example

const currentDate = new Date();

const currentHour = currentDate.getHours();
const currentMinute = currentDate.getMinutes();

console.log(`Current time - ${currentHour}:${currentMinute}`);

Output

Current time - 15:29

To convert the hours to a 12-hour format, you can use a simple calculation:

const hours12 = currentHour % 12 || 12;

This expression calculates the remainder of the division of currentHour by 12. If the remainder is 0 (corresponding to 12:00 PM or 12:00 AM), it returns 12; otherwise, it returns the remainder.

To ensure that minutes are always displayed as two digits (e.g., “05” instead of “5”), you can format it like this:

// Get current date and time
const now = new Date();

// Get hours and minutes
const hours = now.getHours();
const minutes = now.getMinutes();

const formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
console.log(`Current time: ${hours}:${formattedMinutes}`);

Output

Current time: 12:30

That’s it!