Home > Database > Mysql Tutorial > How to Convert a PHP Date to MySQL\'s DATE or DATETIME Format?

How to Convert a PHP Date to MySQL\'s DATE or DATETIME Format?

Barbara Streisand
Release: 2024-11-27 06:37:09
Original
827 people have browsed it

How to Convert a PHP Date to MySQL's DATE or DATETIME Format?

Converting PHP Date to MySQL Format

When working with a PHP date field, it may be necessary to convert it to the MySQL format of 0000-00-00 before inserting it into the database. This can be achieved through various methods depending on the specific format of the PHP date.

Converting Date for DATE Column Type

If the MySQL column is of type DATE, which stores only the date portion and not the time, use the following code:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
Copy after login

This code converts the dash-separated date in PHP to a slash-separated format that strtotime() can correctly parse. The date is then formatted in the required MySQL format.

Converting Date for DATETIME Column Type

If the MySQL column is of type DATETIME, which stores both the date and time components, use the following code:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));
Copy after login

This code includes the time component in the conversion.

Alternate Method

If the PHP date does not follow a consistent format that can be converted using strtotime(), an alternative method is to use a regular expression to parse and reformat the date:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '-- ', $date);
Copy after login

This regular expression rearranges the date and time components into the required MySQL format.

The above is the detailed content of How to Convert a PHP Date to MySQL\'s DATE or DATETIME 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