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

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

Patricia Arquette
Release: 2024-10-29 12:10:29
Original
1038 people have browsed it

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

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

Question:

Attempting to convert a date from dd/mm/yyyy to yyyy-mm-dd has proven unsuccessful despite utilizing mktime() and other functions. While successful in splitting the original date using the '/' delimiter, the challenge lies in modifying the format and replacing '/' with '-'.

Answer:

Converting Date Formats Using Default Function

PHP's default date function can be employed for this conversion:

<code class="php">$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );</code>
Copy after login

Custom Solution

However, testing has revealed that PHP encounters issues with the dd/mm/yyyy format. Consider this alternative solution:

<code class="php">$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));</code>
Copy after login

Explanation

The str_replace() function replaces '/' with '-' in the $date variable, which is then converted to the desired yyyy-mm-dd format using the date() function.

The above is the detailed content of How to Convert a Date 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