How to Convert DateTime to String in PHP
If you wish to manipulate with the DateTime object in PHP, then this snippet is for you. Here, you will learn how to correctly convert DateTime to string.
Manipulating date and time is among the most common tasks 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 format method DateTime
<?php
$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');
?>The format() method always returns a string, so explicit error handling for failure is unnecessary.
Using Type Casting
An alternative and simpler way to convert a DateTime object to a string is by casting it directly. This calls the object's __toString() method, which returns the date in ISO-8601 format.
Here is how it looks:
php DateTime cast to string
<?php
$date = new DateTime('2000-01-01');
$result = (string) $date;
echo $result; // Outputs: 2000-01-01T00:00:00
?>For immutable date handling, consider using DateTimeImmutable, which works identically but prevents accidental modification of the original object.
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.