Home > Backend Development > PHP Tutorial > Why Does strtotime() Fail with dd/mm/YYYY Dates, and How Can I Fix It?

Why Does strtotime() Fail with dd/mm/YYYY Dates, and How Can I Fix It?

Patricia Arquette
Release: 2024-12-11 16:52:11
Original
163 people have browsed it

Why Does strtotime() Fail with dd/mm/YYYY Dates, and How Can I Fix It?

strtotime() Fails to Handle dd/mm/YYYY Format

The strtotime() function proves particularly useful for date handling. However, it lacks comprehensive documentation on supported date formats, particularly when it comes to dd/mm/YYYY. Attempts to use this format in strtotime() fail, with only the mm/dd/YYYY format being recognized.

Converting dd/mm/YYYY to YYYY-mm-dd

Explode() can be employed to solve this issue, but a simpler approach exists. To convert a dd/mm/YYYY date to YYYY-mm-dd format:

  1. Replace all slashes (/) with dashes (-): $date = str_replace('/', '-', $date);
  2. Use strtotime() to parse the modified date string and format it using date(): echo date('Y-m-d', strtotime($date));

Example:

$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));
Copy after login

Output:

2010-05-25

Note:

The strtotime() documentation clarifies: "Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed."

The above is the detailed content of Why Does strtotime() Fail with dd/mm/YYYY Dates, and How Can I Fix It?. 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