Styphon
Styphon

Reputation: 10447

Difficulty converting time between timezones

I'm trying to convert Midnight GMT into different time zones. We have a daily quiz that runs from midnight to midnight, and I'd like to be able to dynamically display the different time zones to people so it automatically changes with DST.

Following this answer I came up with this code

$dateFormat = 'h:i a';
$date = new DateTime(gmdate('Y-m-d'), new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone('Europe/London'));
$tzWesternEurope = date($dateFormat);
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
$tzCentralEurope = date($dateFormat);
$date->setTimezone(new DateTimeZone('Europe/Athens'));
$tzEasternEurope = date($dateFormat);
// ... And so for 17 different time zones around the world.

However it doesn't work. As you can see from this eval.in example all of the time zones show the same, and show the wrong time. What am I doing wrong?

I've tried changing gmdate('Y-m-d') to a time, 00:00 and 12am but neither worked. I've tried using UTC instead of GMT as the base DateTimeZone, but again no difference.

Upvotes: 0

Views: 47

Answers (1)

John Conde
John Conde

Reputation: 219794

You're never actually using $date. You keep changing the timezone but then you ignore it and go straight to the date() function which is completely unrelated.

You need to use DateTime::format() to output the date in the format and timezone you want.

$dateFormat = 'h:i a';
$date = new DateTime(null, new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone('Europe/London'));
$tzWesternEurope = $date->format($dateFormat);
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
$tzCentralEurope = $date->format($dateFormat);

Upvotes: 2

Related Questions