MySQL STR_TO_DATE() Function
MySQL STR_TO_DATE() Function
The MySQL STR_TO_DATE() function parses a formatted string into a MySQL DATE, TIME, or DATETIME value. It works as the exact inverse of DATE_FORMAT().
CSV imports, third-party webhooks, and legacy text columns often store dates in non-ISO formats like '10/05/2026' or 'May 10, 2026 02:30 PM'. MySQL cannot compare or index these strings chronologically until you convert them with STR_TO_DATE().
Depending on which specifiers appear in format, STR_TO_DATE() automatically returns DATE (only date parts), TIME (only time parts), or DATETIME (both).
Syntax
STR_TO_DATE(str, format)
str: The input string containing the date or time text.format: Format string using MySQL specifiers like%Y,%m,%d,%H,%i,%s,%M, and%p.
Practical Example
Suppose demo_orders imports raw checkout strings like '10-May-2026 04:15 PM' in raw_order_text. You can convert them into sortable DATETIME values.
SELECT
order_id,
raw_order_text,
STR_TO_DATE(raw_order_text, '%d-%b-%Y %h:%i %p') AS parsed_datetime
FROM demo_orders
WHERE order_id BETWEEN 701 AND 703;
| order_id | raw_order_text | parsed_datetime |
|---|---|---|
| 701 | 10-May-2026 04:15 PM | 2026-05-10 16:15:00 |
| 702 | 02-Jun-2026 09:05 AM | 2026-06-02 09:05:00 |
| 703 | invalid-date | NULL |
Row 703 returns NULL cleanly instead of crashing the SELECT query when the string does not match the expected pattern.
Common Mistakes & NULL Behavior
STR_TO_DATE() returns NULL whenever str fails to match format or produces an invalid calendar date (such as '2026-02-30' or '2026-13-01'). Always check for NULL results before inserting parsed values into NOT NULL columns.
A frequent bug is mixing %h (12-hour clock 01β12) with %H (24-hour clock 00β23), or forgetting %i for minutes (%m means numeric month, not minutes!). Also remember %p (AM/PM) only applies when paired with a 12-hour specifier like %h or %l.
If str or format is NULL, STR_TO_DATE() returns NULL. Unspecified date parts default to 0, and unspecified time parts default to 00:00:00.
Frequently Asked Questions
Why did STR_TO_DATE('2026-05-10 14:30', '%Y-%m-%d %H:%m') return NULL?
%m represents the month (01β12), not minutes. Minutes use %i, so the correct format is '%Y-%m-%d %H:%i'.
Does STR_TO_DATE() ignore extra text at the end of a string?
Yes. Extra characters at the end of str that follow a full match are ignored, though mismatches earlier in the string return NULL.
What return type does STR_TO_DATE() produce?
It returns DATE if only date specifiers are present, TIME if only time specifiers are present, and DATETIME when both appear.
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.