Extracting only date from datetime field in MySQL and assigning it to PHP variable?

In PHP, you can extract only the date from a MySQL datetime field using the DateTime class. This is useful when you need to display or process only the date portion without time information.

Syntax

DateTime::createFromFormat("Y-m-d H:i:s", yourDateTimeValue)->format("yourFormatSpecifier");

Example

Here's how to extract only the date from a MySQL datetime value ?

<?php
$MySQLDataBaseDateTime = "2018-02-13 13:10:15";
echo DateTime::createFromFormat("Y-m-d H:i:s", $MySQLDataBaseDateTime)->format("d/m/Y");
?>
13/02/2018

Different Date Formats

You can format the extracted date in various ways by changing the format specifier ?

<?php
$MySQLDataBaseDateTime = "2018-02-13 13:10:15";
$dateObj = DateTime::createFromFormat("Y-m-d H:i:s", $MySQLDataBaseDateTime);

echo "Y-m-d format: " . $dateObj->format("Y-m-d") . "
"; echo "F j, Y format: " . $dateObj->format("F j, Y") . "
"; echo "d-M-Y format: " . $dateObj->format("d-M-Y") . "
"; ?>
Y-m-d format: 2018-02-13
F j, Y format: February 13, 2018
d-M-Y format: 13-Feb-2018

Conclusion

The DateTime class provides an efficient way to extract and format dates from MySQL datetime fields. Use createFromFormat() to parse the datetime string and format() to display it in your desired format.

Updated on: 2026-03-15T08:10:15+05:30

791 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements