Home >Database >Mysql Tutorial >How to Convert a PHP Date to MySQL\'s YYYY-MM-DD (or YYYY-MM-DD HH:MM:SS) Format?

How to Convert a PHP Date to MySQL\'s YYYY-MM-DD (or YYYY-MM-DD HH:MM:SS) Format?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 11:12:11537browse

How to Convert a PHP Date to MySQL's YYYY-MM-DD (or YYYY-MM-DD HH:MM:SS) Format?

Converting PHP Date to MySQL Format

When working with dates in both PHP and MySQL, it's essential to have a consistent format for easy integration. In this case, you want to convert a PHP date to the MySQL format of 0000-00-00.

To achieve this, you can utilize the date() and strtotime() functions. However, it's important to note that strtotime() doesn't recognize dashes (-), so you need to substitute them with slashes (/).

$date = mysql_real_escape_string($_POST['intake_date']);
$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

The str_replace() function converts any dashes (-) in the date string to slashes (/), making it compatible with strtotime(). The resulting date will be in the required YYYY-MM-DD format for MySQL.

Alternatively, if your MySQL column is of the DATETIME type, which includes time, use the following code:

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

If your date is formatted differently, such as "02/07/2009 00:07:00," you can use regular expressions to reformat it before converting it:

$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '-- ', $date);

This will rearrange the date into the YYYY-MM-DD HH:MM:SS format.

Remember to mysql_real_escape_string() the date before inserting it into your database to prevent SQL injections.

The above is the detailed content of How to Convert a PHP Date to MySQL\'s YYYY-MM-DD (or YYYY-MM-DD HH:MM:SS) Format?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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