Home > Database > Mysql Tutorial > How Can I Parse Date Strings into MySQL DATE or DATETIME Values?

How Can I Parse Date Strings into MySQL DATE or DATETIME Values?

Susan Sarandon
Release: 2024-12-01 05:41:14
Original
894 people have browsed it

How Can I Parse Date Strings into MySQL DATE or DATETIME Values?

Parsing Dates for MySQL

MySQL provides robust functions for manipulating date and time values. One common task is converting string representations of dates into a format suitable for insertion or update into TIMESTAMP or DATE fields.

STR_TO_DATE(): The Inverse of DATE_FORMAT()

While the DATE_FORMAT() function can format dates, its inverse is the STR_TO_DATE() function.

Syntax:

STR_TO_DATE(str, format)
Copy after login

Parameters:

  • str: The string representation of the date.
  • format: A string specifying the format of the input date.

Usage:

STR_TO_DATE() parses the input string using the specified format and returns a DATETIME, DATE, or TIME value accordingly. If the extracted value is invalid, it returns NULL and generates a warning.

Example: Parse Date Constant

Consider the string representation of a date:

'15-Dec-09'
Copy after login

To convert this string into a DATE value, we can use the following query:

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

This query parses the string using the format '%d-%b-%y', where '%d' represents the day of the month, '%b' represents the abbreviated month name, and '%y' represents the year with two digits.

Output:

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

Now, the parsed DATE value can be used for insertion or update operations in MySQL TIMESTAMP or DATE fields.

The above is the detailed content of How Can I Parse Date Strings into MySQL DATE or DATETIME Values?. 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