Creating a timezone form item using Date API
This is simple. Just use the 'date_timezone' type, which is provided by date_api.module.
$form['timezone'] = array( '#type' => 'date_timezone', '#default_value' => $timezone, '#description' => "Select a timezone if all the events will happen in the same place. Select that place's timezone", );
Converting to and from UTC
In the new system you just need to know the timezone name and either the UTC or local time. We store the UTC time and the timezone name in the database (in two separate fields). We retrieve that data and do:
$date = the UTC value from the database $local_zone = the name of the local timezone $type = the type of date value, DATE_DATETIME, DATE_ISO, or DATE_UNIX $date = date_make_date($date, 'UTC', $type); date_timezone_set($date, timezone_open($local_zone)); $date now contains the local value of the date. Output it like: print date_format_date($date, 'custom', 'm/d/Y H:i');
To convert a local date back to UTC to store it in the database, do:
$date = local date value $local_zone = the name of the local timezone $type = the type of date value, DATE_DATETIME, DATE_ISO, or DATE_UNIX $date = date_make_date($date, $local_zone, $type); date_timezone_set($date, timezone_open('UTC')); $date now contains the UTC value of the date. Output it like: print date_format_date($date, 'custom', 'm/d/Y H:i');
Use of timezone abbreviations
The API doesn't handle timezone abbreviations at all, there's no way to do it right because they are not unique (EST could be Eastern Standard Time or European Summer Time). We need the full, undeprecated timezone name, which looks like 'America/Chicago'. It is comprised of the name of the continent and the major city in the timezone. Older names like 'US/Central' are deprecated because the area names change, but city names rarely do. Some good info about timezones is at http://en.wikipedia.org/wiki/Zoneinfo.
Also, we do not use spaces in the timezone names, so we use America/New_York, not America/New York. The PHP 5.2 date functions and MYSQL native timezone handling all expect names without spaces in them to work correctly.
You can use the php function
timezone_name_from_abbr() to try to translate to and from abbreviations, but it's not entirely reliable, as noted above. If we have the current offset and we know if it's currently daylight savings time or not, you can combine that with the abbreviation to get the timezone name, but that's a lot of 'if's.