Course contentsShow
← JavaScript
Lesson 1623 of 2,72335. Standard Library and Built-insFree lesson

Getting Time Components: getHours, getMinutes, getSeconds

Retrieve time-of-day values including hours, minutes, seconds, and milliseconds from Date objects.

Getting Time Components: getHours, getMinutes, getSeconds

You'll learn how to extract the hour, minute, second, and millisecond values from a Date object to work with time-of-day information.

Understanding Time Components

Just like how getFullYear(), getMonth(), and getDate() let you extract calendar information, JavaScript provides methods to retrieve the time-of-day portion of a Date object. Think of a Date as a timestamp that contains both "when" (the calendar date) and "what time" (hours, minutes, seconds). These getter methods let you read the clock portion separately.

The Time Extraction Methods

The Date object provides four methods for extracting time components:

const now = new Date('2024-03-15T14:35:27.892Z');

const hours = now.getHours();        // 14 (2 PM in 24-hour format)
const minutes = now.getMinutes();    // 35
const seconds = now.getSeconds();    // 27
const milliseconds = now.getMilliseconds(); // 892

All of these return integers representing the local time component. Hours range from 0-23, minutes and seconds from 0-59, and milliseconds from 0-999.

Local Time vs UTC

These methods return values in your local timezone. JavaScript also provides UTC equivalents: getUTCHours(), getUTCMinutes(), getUTCSeconds(), and getUTCMilliseconds() for working with coordinated universal time.

const date = new Date('2024-03-15T23:30:00Z');
const localHour = date.getHours();     // Depends on your timezone
const utcHour = date.getUTCHours();    // Always 23

Practical Use

These methods are essential for displaying custom time formats, filtering events by time of day, or performing time-based calculations.

Key Takeaway: Use getHours(), getMinutes(), getSeconds(), and getMilliseconds() to extract time-of-day components from Date objects, remembering these return local time unless you use their UTC variants.