Daniel
Daniel

Reputation: 1

PHP Display local time (static) and consider summertime/wintertime

I'm currently working on trying to display local times for 10 different time zones and I can't find any solution for my problem.

I'm using this code:

$timezone = +12;
echo gmdate("Y/m/j H:i:s<br />", time() + 3600*($timezone + date('I'))); 

Where $timezone is the local time, either +, -, or none depending on the time zone. My problem is, that some countries have summer time. How can I make this code take this into account and calculate for summertime/wintertime as well?

Upvotes: 0

Views: 1382

Answers (2)

Janos Pasztor
Janos Pasztor

Reputation: 1275

You shouldn't do "manual" date calculations like this, PHP has very good functions for that. For timezone calculations use DateTimeZone.

Solution

Although I'm not entirely sure what you wish to achieve, you can convert between timezones like this:

$fromTz = new DateTimeZone('GMT');
$toTz   = new DateTimeZone('Pacific/Midway');
$dt     = new DateTime('now', $fromTz);
$dt->setTimezone($toTz);
echo $dt->format('Y/m/j H:i:s');

Background

Timezone calculations can be extremely tricky, especially – as you noticed – in conjunction with Daylight Saving Time (DST). Also, every few years a country changes timezone, etc. You should also not forget about the time corrections that are applied even to UTC to match the planet's rotation exactly.

The timezone data that PHP uses has a record of all these changes and can apply timezone calculations precisely, which is a lot more than you can hope to accomplish when writing your own code.

On more details why you shouldn't do time calculations with timestamps read my blogpost about time handling.

Upvotes: 2

Noqomo
Noqomo

Reputation: 168

As mentioned, you should use PHP's time and date functions, however it is important that PHP's date/time data is up to date.

However, PHP is not updated as frequently as the Olson DB (used for time and date records), so just using PHPs time zone conversions may leave you with outdated DST information, and influence the correctness of your data. While this is not expected to happen frequently, it may happen, and will happen if you have large base of users worldwide.

To cope with the above issue there is a pecl package which will update PHP's TimeZone data. Install this package as frequently as it is updated, and you are at a very good standpoint.

Upvotes: 2

Related Questions