MySQL DATE_FORMAT function
MySQL's function for rendering a date or timestamp as text, using %-prefixed specifiers from %Y (4-digit year) to %r (12-hour time). It does the job TO_CHAR does on PostgreSQL and Oracle.
- Категория
- Dates & times
- Returns
string- In this category
- 10 of 121
Синтаксис
DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s')
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Not built in | FORMAT(d, 'yyyy-MM-dd') or CONVERT style codes |
| PostgreSQL | Not built in | TO_CHAR(ts, 'YYYY-MM-DD') |
| MySQL | Да | Supported under this name. |
| SQLite | Not built in | strftime('%Y-%m-%d', ts), with mostly different codes |
| Oracle | Not built in | TO_CHAR(d, 'YYYY-MM-DD') |
Примеры
MySQL
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month, COUNT(*) AS orders FROM orders GROUP BY month;
MySQL
SELECT DATE_FORMAT(created_at, '%W %d %M %Y %r') AS pretty FROM orders;
Полезно знать
- %i is minutes (not %M, which is the full month name) and %H is 24-hour hours: the two most-mistyped specifiers.
- Week numbers: %U starts weeks on Sunday and %u on Monday. For ISO 8601 weeks use %v together with %x, the matching ISO year.
- DATE_FORMAT(d, '%Y-%m') returns a string that sorts correctly, which is fine for grouping. Keep the original column for filtering, so an index on it can still be used.
Questions about DATE_FORMAT
What is the DATE_FORMAT code for month name?
%M gives the full name (August), %b the abbreviation (Aug). Be careful: %m is the number 08, not the name.
What is the equivalent of DATE_FORMAT in PostgreSQL?
TO_CHAR, with different codes: TO_CHAR(ts, 'YYYY-MM') for the same output as DATE_FORMAT(ts, '%Y-%m').
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Get the first day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Format a date as text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Round timestamps to the nearest minute or hour in SQL Snippet
- Group rows into hourly buckets Snippet
Cheat sheets for the engines that have it: MySQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.