Convert a Date Format in PHP
You may encounter a scenario where you need to reformat a date from yyyy-mm-dd to dd-mm-yyyy without using SQL. However, the date function in PHP typically requires a timestamp, and extracting a timestamp from a string can be challenging.
To overcome this hurdle, you can utilize the following approach:
use DateTime; use DateTimeZone; $originalDate = "2010-03-21"; $timestamp = strtotime($originalDate); // Convert to a timestamp // Option 1: Using DateTime $dt = new DateTime(); $dt->setTimestamp($timestamp); $newDate = $dt->format('d-m-Y'); // Reformat the date // Option 2: Using date() with strtotime() $newDate = date("d-m-Y", $timestamp);
The strtotime() function converts the string representation of the date into a timestamp. Subsequently, you can use either DateTime or date() to reformat the date according to your desired format.
Note:
While this approach provides a simple solution, it might not be suitable for all conversion scenarios. For more complex date conversions, consider using the DateTime class for parsing and formatting.
The above is the detailed content of How to Convert 'yyyy-mm-dd' to 'dd-mm-yyyy' Date Format in PHP Without Using SQL?. For more information, please follow other related articles on the PHP Chinese website!