Home > Database > Mysql Tutorial > How Can I Parse Dates from Strings for MySQL Database Insertion?

How Can I Parse Dates from Strings for MySQL Database Insertion?

DDD
Release: 2024-12-03 09:21:11
Original
993 people have browsed it

How Can I Parse Dates from Strings for MySQL Database Insertion?

Parsing Dates for MySQL Insertion

MySQL provides functions for both formatting and parsing dates. While DATE_FORMAT() is used for conversion from dates to strings, its inverse, STR_TO_DATE(), enables the conversion of strings into dates.

Using STR_TO_DATE()

The STR_TO_DATE() function takes a string and a format string as parameters. It returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.

For example, to convert the string '15-Dec-09' into a date suitable for insertion into a TIMESTAMP or DATE field in MySQL, we can use the following query:

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

The format string '%d-%b-%y' specifies the format of the input string, with '%d' representing the day, '%b' the abbreviated month name, and '%y' the year (two digits).

This query will return a date value of '2009-12-15', which can then be used for insertion into the database.

The above is the detailed content of How Can I Parse Dates from Strings for MySQL Database Insertion?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template