Convert Unix Timestamp To Readable Date Time in PHP

Convert Unix Timestamp To Readable Date Time in PHP

The epoch time or unix timestamp is used to describe a point in time. It is a number of seconds between date time which elapsed since 00:00:00 Thursday, 1 January 1970 at Coordinated Universal Time (UTC). You have used unix timestamp converter or epoch converter tools online. These tools convert unix timestamp in seconds or milliseconds to human readable date.

So if you're also thinking about making unix timestamp conversion tools using PHP, then you're here at right place. In this tutorial, you will learn how to implement Unix Timestamp conversion to human readable date using PHP. You will also learn how to display GMT date time according to particular timezone using PHP.

We will cover this tutorial in easy steps with live demo to convert unix timestamp to date with PHP.



So let’s start the coding

Step1: Convert Unix Timestamp to PHP DateTime
First we will get unix timestamp and then convert it into PHP date time using PHP DateTime class.
$unix_timestamp = $_POST['timestamp'];
$datetime = new DateTime("@$unix_timestamp");


Step2: Display PHP Date Time in Formatted Form
Now we will display PHP Date Time in formatted form like "02-10-2016 21:05:18".
echo $datetime->format('d-m-Y H:i:s');


Step3: Display PHP Date Time with Specific Timezone
Now we will display PHP date time from UTC time to specific timeozone.
$date_time_format = $datetime->format('Y-m-d H:i:s');
$time_zone_from="UTC";
$time_zone_to='Asia/Kolkata';
$display_date = new DateTime($date_time_format, new DateTimeZone($time_zone_from));
$display_date->setTimezone(new DateTimeZone($time_zone_to));
echo $display_date->format('d-m-Y H:i:s')


Step4: Complete Example Code
Here is complete code to display human readable date time from Unix Timestamp with timezone.
$unix_timestamp = $_POST['timestamp'];
$datetime = new DateTime("@$unix_timestamp");
// Display GMT datetime
echo $datetime->format('d-m-Y H:i:s');
$date_time_format = $datetime->format('Y-m-d H:i:s');
$time_zone_from="UTC";
$time_zone_to='Asia/Kolkata';
$display_date = new DateTime($date_time_format, new DateTimeZone($time_zone_from));
// Date time with specific timezone
$display_date->setTimezone(new DateTimeZone($time_zone_to));
echo $display_date->format('d-m-Y H:i:s')


You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

You may like these posts