<?php
// *********************************************************************
// By Dave Hale - moodtracker.com
// Version: 1.0
//
// DESCRIPTION:
// The TimezoneSelector dynamically creates a <select></select> control.
// It lets you include the current date and time in the given timezone by
// specifying a 1 in the show() method. The date and time format can be
// indicated in the optional string parameter which follows the standard
// php date/time format string.
//
// The select list is sorted by timezone or by the current timezone's time
// if the date/time is requested.
//
// Usage Examples:
//
// Minimum:
// $tzs = new TimezoneSelector("mySelectControlName");
// $tzs->show();
//
// Show Date (default format):
// $tzs = new TimezoneSelector("tz","class=\"mycss\" onchange=\"document.getElementById('frm').submit();\"");
// $tzs->show(1);
//
// Show Date (custom format):
// $tzs = new TimezoneSelector("tz");
// $tzs->show(1,"m-d-Y H:i:s (O)");
//
// ********************************************************************
class TimezoneSelector {
private $name;
private $extra;
private $error;
public function __construct($name, $extra = "") {
$this->error = "";
if (!$name) {
$this->error = "The required 'name' parameter was not given.";
}
$this->name = $name;
$this->extra = $extra;
}
public function show($showDateTime = 0, $dateFormat = "") {
if ($this->error) {
print $this->error;
return;
}
printf('<select %s %s>',
$this->name ? "name=\"" . $this->name . "\"" : "",
$this->extra);
$timezone_identifiers = DateTimeZone::listIdentifiers();
if ($showDateTime) {
foreach($timezone_identifiers as $val) {
$atz = new DateTimeZone($val);
$aDate = new DateTime("now", $atz);
if ($showDateTime) {
$timeArray["$val"] = $aDate->format("U") + $atz->getOffset($aDate) . "|" . $val;
}
else {
$timeArray["$val"] = $val;
}
}
asort($timeArray);
if (!$dateFormat) $dateFormat = "j M Y (g:ia)";
foreach($timeArray as $key => $val) {
$nTz = new DateTimeZone($key);
$nDate = new DateTime("now", $nTz);
printf('<option %s value="%s">%s</option>
', $key == $_POST["$this->name"] ? "selected=\"selected\"" : "", $key, $nDate->format($dateFormat) . " - " . str_replace("_", " ", $key));
}
}
else {
foreach($timezone_identifiers as $val) {
printf('<option %s value="%s">%s</option>', $val == $_POST["$this->name"] ? "selected=\"selected\"" : "", $val, str_replace("_", " ", $val));
}
}
print "</select>";
}
}
?>