How to use the MySQL HOUR() function
MySQL HOUR() is a function that returns the hour part of a date or time value. It can be used to extract the hour from a datetime, date, or time expression.
MySQL HOUR() is a function that returns the hour part of a date or time value. It can be used to extract the hour from a datetime, date, or time expression. The function takes one argument: the date or time value. The return value is an integer from 0 to 838, representing the hour in 24-hour format.
Syntax
The syntax of the function is:
HOUR(date_or_time)
The parameter is:
date_or_time
: The date or time value to extract the hour from. It can be a datetime, date, or time expression, or a string in a valid date or time format.
Examples
Some examples of using the function are:
-
To get the hour part of the current time, use:
SELECT HOUR(CURTIME());
The result is:
10
This means that the current time is 10:20:21.
-
To get the hour part of a datetime value, use:
SELECT HOUR('2023-11-15 16:45:12');
The result is:
16
This means that the datetime value has 16 as the hour part.
-
To get the hour part of a time value, use:
SELECT HOUR('18:30:00');
The result is:
18
This means that the time value has 18 as the hour part.
-
To get the hour part of a string in a valid date or time format, use:
SELECT HOUR('11/15/2023 4:45:12 PM');
The result is:
16
This means that the string is converted to a datetime value and has 16 as the hour part.
-
To format a datetime value using the hour part, use:
SELECT DATE_FORMAT('2023-11-15 16:45:12', '%H:%i');
The result is:
16:45
This means that the datetime value is formatted as hour:minute, using the 24-hour clock.
Similar Functions
Some similar functions to HOUR() are:
MINUTE()
: This function returns the minute part of a date or time value, from 0 to 59.SECOND()
: This function returns the second part of a date or time value, from 0 to 59.MICROSECOND()
: This function returns the microsecond part of a date or time value, from 0 to 999999.EXTRACT()
: This function extracts a specific part of a date or time value, such as year, month, day, hour, minute, second, or microsecond.