"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert a PHP Date to MySQL \"YYYY-MM-DD\" Format?

How to Convert a PHP Date to MySQL \"YYYY-MM-DD\" Format?

Published on 2024-11-08
Browse:115

How to Convert a PHP Date to MySQL \

Converting PHP Date to MySQL Format

When working with dates in PHP and MySQL, it's essential to format them correctly for proper insertion into the database.

The question arises: How can we convert a PHP date into the MySQL format of "YYYY-MM-DD"?

Assume we have a date field in PHP set as:

$date = mysql_real_escape_string($_POST['intake_date']);

To convert this PHP date to MySQL format, consider the following:

If the MySQL column is of the DATE type:

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

If the MySQL column is of the DATETIME type:

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

It's important to note that strtotime() will not work with hyphen (-) separators. Therefore, it's necessary to replace the hyphens with slashes before using strtotime().

Alternatively, for the date format you provided, which includes time, you can also use this regular expression based approach:

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

This will output the correct MySQL format of "YYYY-MM-DD HH:MM:SS".

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3