Format DateTime in PHP
To format a DateTime in PHP we have mainly three options:
Let’s see theese methods more in-depth with some examples in the next sections.
Format Timestamp using the Date() function
The date() function returns a formatted string starting from a format string and a timestamp. If no timestamp is specified, the default value will be the result of the time() function (the current timestamp).
To format a timestamp to a string using the date() function you can use the following snippet as example:
$format = date('d/m/y H:i:s', 1621371929);
echo $format;
The output is:
18/05/21 14:05:29
Format DateTime using date_format() function
The date_format function returns a string and accepts two parameters: the first argument must be of type DateTimeInterface
and the second argument is the string format.
In the following snippet, we use the date_create() function to create the DateTimeInterface from a given Timestamp, and date_format() to convert it into a string:
$date = date_create(1621371929);
echo date_format($date, 'd/m/y H:i:s');
and the output is:
18/05/21 14:05:29
Format DateTime using DateTime::format()
The last example we see is using the DateTime::format() method from the DateTime class in PHP.
Firstly, we need to create a DateTime object starting from a DateTime string. After, we will call the format() method which returns a formatted string according to the format string passed as argument.
To format a DateTime object in PHP you can use the following snippet as example:
$date = new DateTime('2021-05-18 14:05:29');
echo $date->format('d/m/y H:i:s');
and the output is:
18/05/21 14:05:29
For more advanced use of DateTime::format(), you can read our article on How to convert DateTime to String in PHP.