简体   繁体   中英

How to convert UTC datetime to another timezone?

How can i convert a date like this: 2012-07-16 01:00:00 +00 (it's in the UTC +00:00 timezone) to UTC +04:00 timezone? Ensuring that daylight saving will be handelled correctly?

Use DateTime and DateTimeZone .

$date = new DateTime('2012-07-16 01:00:00 +00');
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04

echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00 

To help with the solution, you need to get the last part of the string (the offset part) and look it up against a simple lookup. you can use a regex or substr() (maybe) to get the offest part. Then, when you have a + or - value, use a maximum of 24 lookups against possible timezones which you can use with PHP's possible timezones - if the offset is the same, who cares what the actual country/location is?

The use date_default_timezone_set to apply the right one.

You can also use GMT time also and convert it to your requirement afterwards

<?php
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

GMT refers Greenwich Mean Time which is common all over the world.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM