How to Convert DateTime to String in PHP

Manipulating with date and time is among the most common issues in PHP. In this tutorial, we have chosen the most straightforward and efficient ways of converting the DateTime object to string in PHP.

Using the format Method

The first method we recommend to use for converting the DateTime object to a string is format.

Here is the code to run:

<?php

$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

?>

In case format doesn’t succeed, it returns FALSE. In several applications, it would be best if you handled the failing case like here:

<?php

if ($result) {
    echo $result;
} else {
    // format failed
    echo "Unknown Time";
}

?>

Using the list Method

An alternative method to convert to convert the DateTime object to string is using list.

With it, it is possible to do anything with the date component.

Here is how a shorter way of using list looks like:

<?php

list($day, $month, $year, $hour, $min, $sec) = explode("/", date('d/m/Y/h/i/s'));
echo $month . '/' . $day . '/' . $year . ' ' . $hour . ':' . $min . ':' . $sec;

?>

In our snippet, we have covered some of the possible solutions to the issue of converting DateTime to string with PHP. For more solutions and additional information, you can check out this page.