Databases 4 min read

Master MySQL: Converting Between Strings and Dates Made Simple

This guide explains how MySQL handles string‑date conversions, shows when to use date_format for query conditions, warns about performance impacts, demonstrates converting query results with str_to_date, and clarifies the meaning of common format placeholders.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Master MySQL: Converting Between Strings and Dates Made Simple

String Dates in the Database

When a MySQL column stores dates as strings, two scenarios arise: the string follows the standard yyyy-mm-dd or yyyy-mm-dd HH:mm:ss format, which can be queried directly, or it uses a non‑padded format such as 2020-3-15, which leads to incorrect lexical comparisons.

select * from tb_user where date_time > '2020-03-15'

If the stored string lacks leading zeros, the comparison may treat 2020-3-15 as greater than 2020-10-15 because the month part is compared as a string.

Using date_format for Query Conditions

To handle non‑standard string dates, wrap the column with date_format to normalize it before comparison:

select * from tb_user where date_format(date_time,'%Y-%m-%d') > '2020-03-15'

Although functional, this approach forces MySQL to format each row before filtering, which can degrade performance. Therefore, storing dates in proper date/datetime types is recommended.

Converting Result Dates

When the query returns dates in a compact format like yyyy-m-d (e.g., 2020-1-1), use str_to_date to convert the string to a true datetime value:

select str_to_date(date_time,'%Y-%m-%d %H:%i:%s')

Placeholder Meaning Table

The format specifiers used in date_format and str_to_date are:

%Y – year (four digits)

%c – month (numeric, no leading zero)

%d – day of month (two digits)

%H – hour (00‑23)

%i – minutes

%s – seconds

By applying these functions correctly, you can reliably compare and display dates stored as strings in MySQL.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SQLmysqlDate Conversiondate_formatstr_to_date
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.