What are some best practices for storing and retrieving dates in a PHP application?

When storing and retrieving dates in a PHP application, it's important to use the proper data type and format to ensure consistency and accuracy. One common practice is to store dates in a database using the DATETIME data type, which allows for easy sorting and manipulation. When retrieving dates from the database, it's recommended to use PHP's DateTime class to handle date formatting and calculations.

// Storing a date in a MySQL database using PDO
$date = new DateTime('2022-01-01');
$formattedDate = $date->format('Y-m-d H:i:s');

$stmt = $pdo->prepare("INSERT INTO table_name (date_column) VALUES (:date)");
$stmt->bindParam(':date', $formattedDate);
$stmt->execute();

// Retrieving a date from a MySQL database using PDO
$stmt = $pdo->prepare("SELECT date_column FROM table_name WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();

$date = new DateTime($row['date_column']);
echo $date->format('Y-m-d H:i:s');