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
Release: 2024-12-13 21:23:17
Original
608 people have browsed it

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

Output:

2010-05-25
Copy after login

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!

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