Writing a plugin that requires a correct timezone object ? Not sure how to deal with wordpress installations that may not need daylight saving functionality and so have not installed the automatic timezone plugin?
Convert the wordpresss offset into a timezone object
I decided that I had to deal with this and so needed to convert a wordpress offset into a timezone object for my plugin to work correctly. I did not want to insist that the automatic timezone plugin be installed if that web had no need for it, just so my plugin would work.
Wordpress offset for timezone
Define a default set of timezones for each possible offset. Use the offset to lookup the default time zone, and use that timezone for my date and time calculations.
The test code looks like this:
<?php
/* http://webdesign.anmari.com/ Anna-marie Redpath*/
function amr_getTimeZone($offset) {
$timezones = array(
'-12'=>'Pacific/Kwajalein',
'-11'=>'Pacific/Samoa',
'-10'=>'Pacific/Honolulu',
'-9.5'=>'Pacific/Marquesas',
'-9'=>'America/Juneau',
'-8'=>'America/Los_Angeles',
'-7'=>'America/Denver',
'-6'=>'America/Mexico_City',
'-5'=>'America/New_York',
'-4.5'=>'America/Caracas',
'-4'=>'America/Manaus',
'-3.5'=>'America/St_Johns',
'-3'=>'America/Argentina/Buenos_Aires',
'-2'=>'Brazil/DeNoronha',
'-1'=>'Atlantic/Azores',
'0'=>'Europe/London',
'1'=>'Europe/Paris',
'2'=>'Europe/Helsinki',
'3'=>'Europe/Moscow',
'3.5'=>'Asia/Tehran',
'4'=>'Asia/Baku',
'4.5'=>'Asia/Kabul',
'5'=>'Asia/Karachi',
'5.5'=>'Asia/Calcutta',
'5.75'=>'Asia/Katmandu',
'6'=>'Asia/Colombo',
'6.5'=>'Asia/Rangoon',
'7'=>'Asia/Bangkok',
'8'=>'Asia/Singapore',
'9'=>'Asia/Tokyo',
'9.5'=>'Australia/Darwin',
'10'=>'Pacific/Guam',
'11'=>'Asia/Magadan',
'11.5'=>'Pacific/Norfolk',
'12'=>'Asia/Kamchatka',
'13'=>'Pacific/Enderbury',
'14'=>'Pacific/Kiritimati'
);
if (isset($timezones[strval($offset)])) return ($timezones[strval($offset)]);
else return false;
}
echo '<h2>Testing</h2>';
date_default_timezone_set('Europe/London'); /* gmt */
$gmt = new DateTime() ;
$i = -12;
while ( $i < 15) {
$tztext = amr_getTimeZone($i);
if ($tztext) {
date_default_timezone_set($tztext);
$now = new DateTime();
$offset = $now->getOffset();
echo $i.' '.$tztext.' '.$offset/3600 ."<br>";
}
$i=$i+(0.25);
}
echo '<h2>Further Testing</h2>';
$timezone_identifiers = DateTimeZone::listIdentifiers();
foreach ($timezone_identifiers as $i => $t) {
date_default_timezone_set($t);
$now = new DateTime();
$offset = $now->getOffset();
echo $t.' ';
print_r (strval($offset/3600));
echo "<br>";
}
?>
Related posts:
- Timezones, WordPress, Ical, Php…. What a lot of fun this can be (not!) Your Ical file may have a timezone specified, the event may...
- Make wp-cron show times in your wordpress timezone wp-cron-dashboard by the prolific wokamoto (OKAMOTO Wataru) is a very simple but useful little plugin – saves having write your...



