Home > Article > Backend Development > How to Convert a PHP Date to MySQL \'YYYY-MM-DD\' 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:
<code class="php">$date = mysql_real_escape_string($_POST['intake_date']);</code>
To convert this PHP date to MySQL format, consider the following:
If the MySQL column is of the DATE type:
<code class="php">$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));</code>
If the MySQL column is of the DATETIME type:
<code class="php">$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));</code>
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:
<code class="php">$date = '02/07/2009 00:07:00'; $date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '-- ', $date); echo $date;</code>
This will output the correct MySQL format of "YYYY-MM-DD HH:MM:SS".
The above is the detailed content of How to Convert a PHP Date to MySQL \'YYYY-MM-DD\' Format?. For more information, please follow other related articles on the PHP Chinese website!