Home  >  Article  >  Database  >  How to Convert dd/mm/yyyy Date Format to MySQL's YYYY-MM-DD Format in PHP?

How to Convert dd/mm/yyyy Date Format to MySQL's YYYY-MM-DD Format in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 06:53:02355browse

How to Convert dd/mm/yyyy Date Format to MySQL's YYYY-MM-DD Format in PHP?

Date in a URL as dd/mm/yyyy

In your code, you are using the strtotime() function to convert a date in the format dd/mm/yyyy to the MySQL format YYYY-MM-DD. However, this function assumes that the first two digits represent the month and the next two digits represent the day, which is not the case for dates in the dd/mm/yyyy format.

To correctly parse and convert the date, you should use the DateTime::createFromFormat() function. This function allows you to specify the format of the date, and returns a DateTime object that you can then convert to the desired format.

Here is an example of how you can use the DateTime::createFromFormat() function to convert a date in the dd/mm/yyyy format to the YYYY-MM-DD format:

$date = DateTime::createFromFormat('d/m/Y', '20/02/2000');
$mysqlDate = $date->format('Y-m-d'); // 2000-02-20

You can then use the $mysqlDate variable in your SQL query.

In addition, the article provides a helpful table showing the different date formats that are supported by the strtotime() and DateTime::createFromFormat() functions.

See also:

  • Compare DateTime objects with comparison operators in PHP

The above is the detailed content of How to Convert dd/mm/yyyy Date Format to MySQL's YYYY-MM-DD Format in PHP?. 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