How to Convert DateTime to String in PHP

In this tutorial, we will explore some of the ways to convert a PHP DateTime object to a string.

 

DateTime to String with the format() method

The PHP DateTime class has a format() method which we can use to create date strings in a customisable format. To use it, create a new DateTime object and store it in a variable, then use ->format() on that variable and pass the desired format of the date as the first argument.

 

$date = new DateTime();
echo $date->format('Y-m-d H:i:s');
2021-06-02 19:40:23

 

The PHP date_format() Method

Another way of getting a date string is to use the PHP date_format() function. First, create a new DateTime object using the date_create_from_format() function then use date_format() and pass the DateTime object as the first argument and the format as the second.

 

$date = date_create_from_format('d M, Y', '02 Jun, 2021');
echo $newFormat = date_format($date,"Y/m/d H:i:s");
2021/06/02 21:19:45

 

Convert DateTime to a String with the list() Function

Another possible way of getting a date string in PHP is to use the list() function to merge a DateTime object that has been exploded into an array.

 

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

 

This method is not as nice as the first two but in some scenarios, this might be the solution you need to use.

date time