What are some best practices for handling time-based operations in PHP when interacting with a database?

When handling time-based operations in PHP when interacting with a database, it is important to ensure that the time zone settings are consistent between PHP and the database to avoid any discrepancies in date and time calculations. One best practice is to store all date and time values in the database in UTC format and then convert them to the desired time zone when displaying to the user.

// Set the default time zone for PHP
date_default_timezone_set('UTC');

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Retrieve a date and time value from the database
$sql = "SELECT created_at FROM table_name WHERE id = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $created_at_utc = new DateTime($row['created_at']);
        $created_at_utc->setTimezone(new DateTimeZone('America/New_York'));
        echo $created_at_utc->format('Y-m-d H:i:s');
    }
} else {
    echo "0 results";
}

$conn->close();