How can DateTime objects be synchronized with a database to ensure consistency in time operations within an application?

When working with DateTime objects in PHP and interacting with a database, it is important to ensure that both the server's time and the database's time are synchronized to avoid inconsistencies in time operations within the application. One way to achieve this is by setting the database's timezone to match the server's timezone. This can be done by executing a query to set the timezone in the database connection before performing any time-related operations.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

// Set the database timezone to match the server timezone
$pdo->exec("SET time_zone = '+00:00'"); // Replace '+00:00' with the server's timezone

// Perform time-related operations with DateTime objects
$now = new DateTime();
echo $now->format('Y-m-d H:i:s');