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.
以上是如何使用 DateTime 類別重新格式化 PHP 中的日期以提高使用者可讀性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!