Home >Backend Development >PHP Tutorial >How to Convert dd/mm/YYYY Dates to YYYY-mm-dd Without explode()?

How to Convert dd/mm/YYYY Dates to YYYY-mm-dd Without explode()?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 21:23:17608browse

How to Convert dd/mm/YYYY Dates to YYYY-mm-dd Without explode()?

strtotime() Incompatible with dd/mm/YYYY Format

The versatile strtotime() function offers an efficient means of converting dates into Unix timestamps. However, its documentation lacks comprehensive details on supported date formats. While the function accepts mm/dd/YYYY format, it fails to recognize its counterpart, dd/mm/YYYY.

To overcome this limitation, we seek alternative solutions to convert dates in dd/mm/YYYY format to YYYY-mm-dd, without resorting to the explode() function.

Simplified Solution:

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

Output:

2010-05-25

Explanation:

This approach leverages the str_replace() function to substitute the forward slashes (/) in the original date string with hyphens (-), making it compatible with the strtotime() function. The subsequent use of date('Y-m-d', ...) ensures the converted date is formatted in the desired YYYY-mm-dd format.

strtotime() Documentation Explanation:

The strtotime() documentation states that dates in "m/d/y" or "d-m-y" formats are interpreted based on the separator used. If a slash("/") appears, the American "m/d/y" format is assumed, whereas a dash("-") or dot(".") indicates the European "d-m-y" format.

The above is the detailed content of How to Convert dd/mm/YYYY Dates to YYYY-mm-dd Without explode()?. 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