How is the date_format function used in SQL?
The DATE_FORMAT function is used to format date and time values, allowing them to be displayed in a specific format.
Grammar:
DATE_FORMAT(date, format)
Parameter:
- The date and time value to be formatted.
- format: used to specify the date and time format of the returned value.
The commonly used format is as follows:
- %Y: year in four digits
- %y: two-digit year
- %m: Month (01-12)
- %c: Month (1-12)
- %d: Date (01-31)
- %e: Date (1-31)
- %H: Hours (00-23)
- %h: hours (01-12)
- %i: minutes (00-59)
- %s: seconds (00-59)
- %p: AM or PM
- Day of the week (Sunday-Saturday)
- %w: Day of the week (0-6, 0 represents Sunday)
- Month name (January-December)
- abbreviation of the day of the week (Sun-Sat)
- Abbreviation of month names (Jan-Dec)
- – Time (in 24-hour format, hh:mm:ss)
- Time (12-hour format, hh:mm:ss AM/PM)
I will go to the store on Monday.
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') AS current_datetime;
Output:
2021-01-01 12:34:56
The above example formats the current date and time as “YYYY-MM-DD HH:MM:SS.”