Reformatting Dates in PHP
When retrieving dates from a database, they often appear in a standard numerical format, such as "2009-08-12" (numeric year - numeric month - numeric day). To improve user readability, it's desirable to reformat dates to a more user-friendly format like "August 12, 2009" (numeric month - numeric date, numeric year).
One effective approach to reformatting dates in PHP involves using the DateTime class. Unlike solutions based on strtotime, this method ensures the correct interpretation of month and day regardless of server locale settings.
To reformat a date using this approach:
Create a DateTime object from the original date:
<code class="php">$date = DateTime::createFromFormat('Y-m-d', $originalDate);</code>
Format the date using the desired format:
<code class="php">$output = $date->format('F j, Y');</code>
For example, assuming the original date is stored in a variable named $date (e.g., $date = $row['date_selected'];), the following code will reformat the date:
<code class="php">$date = DateTime::createFromFormat('Y-m-d', $date); $output = $date->format('F j, Y');</code>
This method provides a robust and consistent way to reformat dates in PHP, ensuring that month and day are interpreted correctly even in different locale environments.
The above is the detailed content of How to Reformat Dates in PHP Using DateTime Class for Improved User Readability?. For more information, please follow other related articles on the PHP Chinese website!