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;
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!