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;
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');
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.
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!
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
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With