Home > Backend Development > PHP Tutorial > How to Convert a PHP Date to MySQL\'s 0000-00-00 Format?

How to Convert a PHP Date to MySQL\'s 0000-00-00 Format?

Linda Hamilton
Release: 2024-10-26 16:44:03
Original
1062 people have browsed it

How to Convert a PHP Date to MySQL's 0000-00-00 Format?

Converting PHP Date to MySQL Format (0000-00-00)

You have a PHP date field that needs to be converted to the MySQL format of 0000-00-00 for database storage. While you've attempted various methods, including using date('Y-m-d' strtotime($date);, they haven't been successful.

The issue lies in the date separator "-" causing problems with strototime(). The correct approach depends on the data type of the MySQL column:

  • DATE Column:
<code class="php">$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));</code>
Copy after login
  • DATETIME Column:
<code class="php">$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));</code>
Copy after login

If the date is formatted differently (e.g., "02/07/2009 00:07:00"), you can use a regular expression to reformat it as follows:

<code class="php">$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '-- ', $date);</code>
Copy after login

Output:

2009-07-02 00:07:00
Copy after login

By implementing these steps, you can convert PHP dates to the MySQL format 0000-00-00. The specific method to use depends on the MySQL column data type and the formatting of the PHP date.

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