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
Patricia ArquetteOriginal
2024-10-29 12:10:29982browse

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>

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>

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!

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