Skip to content
PHP Logo

How can PHP developers utilize functions like DATE_FORMAT in MySQL and DateTime::format in PHP for timestamp formatting?

PHP developers can utilize functions like DATE_FORMAT in MySQL and DateTime::format in PHP for timestamp formatting by converting the timestamp to the desired format using these functions. DATE_FORMAT in MySQL allows developers to format the timestamp directly in the database query, while DateTime::format in PHP can be used to format timestamps retrieved from the database or generated within the PHP code.

php
// Example of using DATE_FORMAT in MySQL
$query = "SELECT DATE_FORMAT(timestamp_column, '%Y-%m-%d') AS formatted_date FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
echo $row['formatted_date'];

// Example of using DateTime::format in PHP
$timestamp = "2022-01-01 12:00:00";
$date = new DateTime($timestamp);
echo $date->format('Y-m-d H:i:s');