Home >Backend Development >PHP Tutorial >How to Convert Dates from dd/mm/yyyy to yyyy-mm-dd in PHP?

How to Convert Dates from dd/mm/yyyy to yyyy-mm-dd in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 10:45:02304browse

How to Convert Dates from dd/mm/yyyy to yyyy-mm-dd in PHP?

PHP Convert Date Format: dd/mm/yyyy to yyyy-mm-dd

Converting dates between different formats can be a common task in programming. In PHP, it's also necessary to consider the ambiguity of dates in the form of dd/mm/yyyy or d-m-y, where the separator determines the format.

To convert a date from dd/mm/yyyy to yyyy-mm-dd, it's important to first determine the format of the input date. The default date function assumes the American m/d/y format. However, if the separator is a dash (-) or a dot (.), the European d-m-y format is assumed.

Solution:

  • If the input date is in the American m/d/y format, the default date function can be used as follows:
$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );
  • If the input date is in the European d-m-y format, a modification is necessary:
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));

By using this approach, you can accurately convert dates between different formats in PHP.

The above is the detailed content of How to Convert Dates from dd/mm/yyyy to yyyy-mm-dd 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