Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert UTC time to local time

Am getting a UTC time from my server like the following format, my requirement is to convert the UTC time to local time. So users can see a user friendly time on their browser based on their timezone. Please help me to solve this issue. Thank you

$utc = "2014-05-29T04:54:30.934Z"

I have tried some methods but not working in my case

First

$time = strtotime($utc);
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;

Second

$time = strtotime($utc .' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;
like image 812
Dibish Avatar asked May 29 '14 05:05

Dibish


People also ask

How to convert UTC time to local timezone in PHP?

Answer. // create a $dt object with the UTC timezone $dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC')); // change the timezone of the object without changing its time $dt->setTimezone(new DateTimeZone('America/Denver')); // format the datetime $dt->format('Y-m-d H:i:s T');

Is PHP time UTC?

The difference between P and p format is that the new p format uses Z for UTC time, while the P format uses +00:00 . The ISO 8601 date format permits UTC time with +00:00 format, or with Z . This means both date formats below are valid: 2020-09-09T20:42:34+00:00.

How can we convert the time zones using PHP?

It's really simple to convert a DateTime from one time zone to another in PHP. Just create a DateTime object using date & time to be converted as the first parameter and the original time zone as the second parameter. Then change the time zone to the desired one using the setTimezone method. That's all!


2 Answers

Simply use a DateTimeZone, eg

$dt = new DateTime($utc);
$tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after

$dt->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s');

Demo ~ http://ideone.com/fkM4ct

like image 157
Phil Avatar answered Oct 13 '22 03:10

Phil


$savedtime = '2019-05-25 00:01:13'; //this is America/Chicago time
$servertime = ini_get('date.timezone');
$time = strtotime($savedtime . $servertime);
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;

display value according to local timezone
2019-05-25 10:31:13  // this is Asia/Kolkata time
like image 34
Ricky Riccs Avatar answered Oct 13 '22 02:10

Ricky Riccs