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

Barbara Streisand
Release: 2024-10-30 20:07:03
Original
342 people have browsed it

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

Converting Date Formats Using PHP: dd/mm/yyyy to yyyy-mm-dd

When working with dates in programming, it is often necessary to convert the format of the date string. One common conversion is changing the format from dd/mm/yyyy (day/month/year) to yyyy-mm-dd (ISO 8601).

Using the Default Date Function

In PHP, the default date function can be used to convert a date string to a different format. The strtotime() function is used to convert the date string to a timestamp, which can then be passed to the date() function to apply the desired format.

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

However, it's important to note that PHP does not natively support the dd/mm/yyyy format. This can lead to unexpected behavior when attempting to convert dates in this format.

Alternative Solution: Using str_replace()

An alternative solution is to manually replace the slashes with dashes using the str_replace() function.

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

This method reliably converts the date from dd/mm/yyyy to yyyy-mm-dd, regardless of the delimiter used in the original date string.

The above is the detailed content of How to Convert dd/mm/yyyy to yyyy-mm-dd Date Format 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