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>
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>
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!