What is the usage of the MySQL dateformat function?
The DATE_FORMAT function in MySQL is used to format date and time values in a specific format.
Syntax:
DATE_FORMAT(date, format)
Description of Parameters:
- Date: The date or time value to be formatted.
- format: the format of a specified date or time.
The commonly used formatting options are as follows:
- %Y: The year in four digits (e.g. 2021).
- %y: Year represented by 2 digits (e.g. 21).
- %m: Month (01-12).
- %d: Date (01-31).
- %H: Hour in 24-hour clock format (00-23).
- %H: The hour in 12-hour clock format (01-12).
- Minutes (00-59).
- %s: Seconds (00-59).
- %p: AM or PM.
I will meet you at the café at 3 o’clock.
I’ll see you at the café at 3.
- Format the date to the year-month-day format:
SELECT DATE_FORMAT(‘2022-01-01’, ‘%Y-%m-%d’);
Result: 2022-01-01 - Format the date in the form of month/day/year:
SELECT DATE_FORMAT(‘2022-01-01’, ‘%m/%d/%Y’);
Result: 01/01/2022 - Format the time into hours:minutes:seconds form in a 12-hour clock:
SELECT DATE_FORMAT(‘2022-01-01 14:30:45’, ‘%h:%i:%s %p’);
Result: 02:30:45 PM
Please be advised:
- The DATE_FORMAT function returns a string, not a date or time type.
- The DATE_FORMAT function can also be used for column names in queries, for example:
SELECT DATE_FORMAT(column_name, format) FROM table_name;
This will format the specified column in the query result.