Home > Database > Mysql Tutorial > body text

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

Barbara Streisand
Release: 2024-11-06 06:53:02
Original
418 people have browsed it

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
Copy after login

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!

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