Convert a Timestamp to a Readable Date or Time in PHP

  1. Use date() Function to Convert a Timestamp to a Date/Time in PHP
  2. Use setTimestamp() Function to Convert a Timestamp to a Date in PHP
  3. Use createFromFormat() Function to Convert a Timestamp to a Date in PHP

In this article, we will introduce methods to convert a timestamp to date in PHP.

  • Using date() function
  • Using setTimestamp() function
  • Using createFromFormat() function

Use date() Function to Convert a Timestamp to a Date/Time in PHP

The date() function converts a timestamp to a human readable date or time. The correct syntax to use this function is as follows

date($format, $timestamp);

It has two parameters. The parameter $format is the date-time format that the timestamp is converted to. The other parameter $timestamp is an optional parameter. It gives the date according to the timestamp passed. If it is omitted, it uses the current date by default.

<?php  
$date = date('d-m-Y H:i:s', 1565600000);
echo "The date is $date.";  
?>

The date format here is day-month-year, and the time format is hour:minute:second.

Output:

The date and time are 12-08-2019 08:53:20.

Use setTimestamp() Function to Convert a Timestamp to a Date in PHP

The built-in setTimestamp() converts the given timestamp to date or time. To set the format of the date we will use format() function.

$datetimeObject->setTimestamp($timestamp); 

Example Codes:

<?php 
$date = new DateTime(); 
$date->setTimestamp(1565600000);  
$variable = $date->format('U = d-m-Y H:i:s'); 
echo "The date and time is $variable.";
?> 

Output:

The date and time are 1565600000 = 12-08-2019 08:53:20.

Use createFromFormat() Function to Convert a Timestamp to a Date in PHP

The built-in function createFromFormat() gets the date by passing the timestamp as a parameter to this function.

DateTime::createFromFormat($format, $time, $timezone);

The variable $format is the format of the date, $time is the time given in string and $timezone tells about the time zone. The first two parameters are the mandatory parameters.

<?php 
// Calling the createFromFormat() function  
$datetime = DateTime::createFromFormat('U', '1565600000'); 
// Getting the new formatted datetime 
$date= $datetime->format('d-m-Y H:i:s'); 
echo "The date and time is $date.";
?> 

The format "d-m-Y H:i:s" displays both date and time.

Output:

The date and time are 12-08-2019 08:53:20.
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - PHP Timestamp

  • Convert a Date to a Timestamp in PHP
  • Related Article - PHP DateTime

  • Get the Last Day of the Month With PHP Functions
  • Convert a Date to a Timestamp in PHP