Home > Database > Mysql Tutorial > How to Convert String Dates to MySQL DATE or TIMESTAMP format?

How to Convert String Dates to MySQL DATE or TIMESTAMP format?

Patricia Arquette
Release: 2024-12-04 04:28:14
Original
220 people have browsed it

How to Convert String Dates to MySQL DATE or TIMESTAMP format?

Converting String to Date for MySQL Insertion/Update

When inserting data into MySQL's TIMESTAMP or DATE fields, ensuring the correct date format is crucial. As DATE_FORMAT() only formats existing dates, how do we convert a string representation like '15-Dec-09' into a date?

Solution: STR_TO_DATE() Function

MySQL provides the STR_TO_DATE() function, which is the inverse of DATE_FORMAT(). It converts a string into a date using a specified format string. The syntax is:

STR_TO_DATE(str,format)
Copy after login

Usage:

To convert '15-Dec-09' into a date with the format 'dd-mmm-yy', use:

SELECT STR_TO_DATE('15-Dec-09', '%d-%b-%y') AS date;
Copy after login

Result:

+------------+
| date       |
+------------+
| 2009-12-15 |
+------------+
Copy after login

The STR_TO_DATE() function successfully converts the string to a date, allowing for its insertion or update into a TIMESTAMP or DATE field in MySQL.

The above is the detailed content of How to Convert String Dates to MySQL DATE or TIMESTAMP format?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template