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
Release: 2024-10-27 10:45:02
Original
524 people have browsed it

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) );
Copy after login
  • 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));
Copy after login

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!

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