Skip to content
PHP Logo

What are the best practices for handling date formatting and conversion between PHP and MySQL when working with timestamps?

When working with timestamps in PHP and MySQL, it is essential to ensure proper date formatting and conversion to avoid any discrepancies. To handle this effectively, it is recommended to use the `DateTime` class in PHP for date manipulation and formatting, and utilize MySQL's `DATE_FORMAT` function to format dates in queries.

php
// Convert a PHP timestamp to MySQL datetime format
$timestamp = time();
$mysqlDatetime = date('Y-m-d H:i:s', $timestamp);

// Convert a MySQL datetime to PHP timestamp
$mysqlDatetime = '2022-01-01 12:00:00';
$timestamp = strtotime($mysqlDatetime);

// Format a MySQL datetime in a query
$query = "SELECT * FROM table WHERE DATE_FORMAT(date_column, '%Y-%m-%d') = '2022-01-01'";