Search code examples
phpdatedatetimetimeiso8601

Getting local time in PHP given a ISO 8601 datetime and timezone


I'm trying to get a local time given an ISO 8601 formatted datetime string in Zulu time, and a timezone string. I read the PHP documentation about the DateTime object and DateTimeZone, and I have tried a lot of stuff, but I cannot seem to get the right local time. What I have right now:

$datetime = '2017-05-29T10:30:00Z'; // I'm getting this value from an API call
$timezone = 'Europe/Prague'; // I'm getting this value from an API call
$date = new \DateTime( $datetime, new \DateTimeZone( $timezone ) );
var_dump( $date->format('H:i') );
// I would expect it to be 12:30 since 29th May for this timezone would be GMT+2, but I get 10:30

So it's obvious I'm missing something about the DateTime and DateTimeZone classes, but I cannot get it right. Can anyone be so kind of helping me?


Solution

  • So I finally got it right, for anyone interested:

    $datetime = '2017-05-29T10:30:00Z'; // I'm getting this value from an API call
    $timezone = 'Europe/Prague'; // I'm getting this value from an API call
    $date = new \DateTime( $datetime, new \DateTimeZone( 'UTC' ) ); // as the original datetime string is in Zulu time, I need to set the datetimezone as UTC when creating
    $date->setTimezone( new \DateTimeZone( $timezone ) ); // this is what actually sets which timezone is printed in the next line
    var_dump( $date->format('H:i') ); // yay! now it prints 12:30