Reputation: 123
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?
Upvotes: 4
Views: 3082
Reputation: 23
Try this code:
date_default_timezone_set("Europe/Prague");
echo date('H:i');
it will print date & time in 24 hours format.
Upvotes: 1
Reputation: 123
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
Upvotes: 2
Reputation: 4065
I think the confusion lies in what timezone YOU are in as opposed to what timezone the datetime string is in. I'm in New Orleans, so my timezone is 'America/Chicago'. I would set that with:
date_default_timezone_set('America/Chicago');
Then, set the timezone of where your datetime string is coming FROM (I'll assume, Europe/Prague):
$datetimePrague = '2017-05-29T10:30:00Z';
$timezonePrague = 'Europe/Prague';
Now, when you create a DateTime object, pass it the datetime and timezone of where the time is coming FROM.
$datePrague = new \DateTime( $datetimePrague, new \DateTimeZone( $timezonePrague ) );
Then, get the timestamp of the DateTime object:
$timestamp = $datePrague->getTimestamp();
Finally, pass that timestamp to the date() function, along with your desired format, and you will have the equivalent of the DateTime in whatever timezone you're in:
date('H:i', $timestamp);
Here is the complete code, assuming I live in New Orleans, and I want to know what the local New Orleans time is for Prague time of 10:30:
<?php
date_default_timezone_set('America/Chicago');
$datetimePrague = '2017-05-29T10:30:00Z';
$timezonePrague = 'Europe/Prague';
$datePrague = new \DateTime( $datetimePrague, new \DateTimeZone( $timezonePrague ) );
$timestamp = $datePrague->getTimestamp();
var_dump(date('H:i', $timestamp));
Upvotes: 1