MySQL DATE_FORMAT() Function
MySQL DATE_FORMAT(): Format Dates and Timestamps as Strings
The DATE_FORMAT() function converts a DATE or DATETIME value into a custom-formatted string using % pattern specifiers. It gives you full control over month names, weekday names, 12- or 24-hour clocks, and separators.
Reporting dashboards use DATE_FORMAT() to generate human-readable labels like 'May 12, 2026' or '2026-Q2' month buckets.
Syntax
Pass the date expression first and the format template string second:
DATE_FORMAT(date_value, format_string)
Common specifiers include:
%Y/%y: 4-digit year (2026) or 2-digit year (26).%M/%b/%m: Full month name (May), short month (May), or zero-padded month (05).%W/%d: Full weekday name (Tuesday) or zero-padded day (12).%H/%h/%i/%s/%p: 24-hour (14), 12-hour (02), minutes (05), seconds (09), andAM/PM.
Practical Example
Suppose your finance team exports monthly labels and readable timestamps from demo_orders.
SELECT
order_id,
created_at,
DATE_FORMAT(created_at, '%b %d, %Y %h:%i %p') AS display_time,
DATE_FORMAT(created_at, '%Y-%m') AS billing_month
FROM demo_orders
WHERE order_id IN (101, 102);
| order_id | created_at | display_time | billing_month |
|---|---|---|---|
| 101 | 2026-05-04 09:05:00 | May 04, 2026 09:05 AM | 2026-05 |
| 102 | 2026-05-12 16:45:30 | May 12, 2026 04:45 PM | 2026-05 |
Using '%Y-%m' keeps monthly labels sortable alphabetically because the 4-digit year comes before the zero-padded month.
Common Mistakes & NULL Behavior
Avoid these frequent errors when formatting dates in MySQL:
- Confusing
%mand%i: In MySQL,%mmeans numeric month,%Mmeans month name, and%imeans minutes. Using%mfor minutes inserts the month number into your clock time. - Invalid dates or
NULLproduceNULL: PassingNULLfor either argument, or passing an invalid date like'2026-02-30', returnsNULL. - Sorting by formatted strings breaks order: Never run
ORDER BY DATE_FORMAT(created_at, '%d/%m/%Y'), which sorts'02/06/2026'before'15/01/2026'. Sort by the rawcreated_atcolumn instead. - Breaking indexes in
WHERE: AvoidWHERE DATE_FORMAT(created_at, '%Y-%m') = '2026-05'. Use a date range filter oncreated_atso MySQL can use indexes.
Frequently Asked Questions
What language do %M and %W use?
MySQL reads the session variable lc_time_names (which defaults to 'en_US'). Changing SET lc_time_names = 'fr_FR'; outputs French month and weekday names.
Can DATE_FORMAT() parse a string back into a DATE?
No. DATE_FORMAT() turns a date into a formatted string. To parse a formatted string back into a DATE, use STR_TO_DATE().
How do I print a literal percent sign in DATE_FORMAT()?
Write %% inside the format string, such as DATE_FORMAT(order_date, '%Y%%'), to output a literal % character.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.