Inside this article we will see the concept i.e Convert Unix Timestamp To Readable Date Time in PHP. Article contains the classified information about Convert a unix timestamp to a human readable date in PHP.
Whenever you work with unix timestamp values then you seen that those values are not user friendly. It gives a long string of digits which is not possible for humans to understand it.
Example
GMT: Wednesday, 14 December 2022 02:05:34 (Readable DateTime)
Unix Timestamp: 1670983953
We will see here the concept of conversion of Unix Timestamp value to Readable Date Time value.
Read More: How To Check If a Database Table Exists With Laravel
Let’s get started.
Step #1: Get Unix Timestamp value
Here, using PHP function time() you can get the UNIX timestamp value.
$unix_timestamp = time();
It will give you the current unix timestamp string.
Suppose, it is 1670984267
Step #2: Convert Unix Timestamp To PHP DateTime
Here, convert it into PHP date time using PHP DateTime class.
$datetime = new DateTime("@$unix_timestamp");
Step #3: Display PHP Date Time in Readable Format
Now, we will display PHP Date Time in Human readable formatted form.
echo $datetime->format('d-m-Y H:i:s');
Step #4: Display PHP Date Time with Specific Timezone
If you want your DateTime to a specific timezone, also you can do that.
Read More: How To Add JQuery Ajax Loading Spinner in Laravel Example
Now, we will display PHP date time from UTC time to specific timezone.
$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')
Complete Code: Application Programming
Let’s create a small application which takes a Unix Timestamp value and convert it into Asia/Kolkata timezone Human readable datetime.
<?php $unix_timestamp = time(); $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 "<br/>"; echo $display_date->format('d-m-Y H:i:s');
Output
14-12-2022 02:28:11
14-12-2022 07:58:11
We hope this article helped you to learn Convert Unix Timestamp To Readable Date Time in PHP in a very detailed way.
Read More: How To Get File Name From a Path in PHP Example
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.