What are common issues when formatting dates in PHP, especially when retrieving them from a database?

Common issues when formatting dates in PHP, especially when retrieving them from a database, include mismatched date formats between the database and PHP, time zone discrepancies, and incorrect handling of null or empty date values. To solve these issues, it is important to ensure that the date format retrieved from the database matches the format expected by PHP, set the correct time zone for date manipulation, and handle null or empty date values gracefully.

// Retrieve date from the database
$dbDate = "2022-01-15 08:30:00";

// Convert database date to PHP DateTime object
$date = new DateTime($dbDate);

// Set the desired output format
$outputFormat = "Y-m-d H:i:s";

// Set the desired time zone
$date->setTimezone(new DateTimeZone('UTC'));

// Format the date
$formattedDate = $date->format($outputFormat);

echo $formattedDate;