How to Check Is Timezone Identifier Valid from Code

How to check is timezone identifier valid from code?

You solution works fine, so if it's speed you're looking for I would look more closely at what you're doing with your arrays. I've timed a few thousand trials to get reasonable average times, and these are the results:

createTZlist  : 20,713 microseconds per run
createTZlist2 : 13,848 microseconds per run

Here's the faster function:

function createTZList2()
{
$out = array();
$tza = timezone_abbreviations_list();
foreach ($tza as $zone)
{
foreach ($zone as $item)
{
$out[$item['timezone_id']] = 1;
}
}
unset($out['']);
ksort($out);
return array_keys($out);
}

The if test is faster if you reduce it to just if ($item['timezone_id']), but rather than running it 489 times to catch a single case, it's quicker to unset the empty key afterwards.

Setting hash keys allows us the skip the array_unique() call which is more expensive. Sorting the keys and then extracting them is a tiny bit faster than extracting them and then sorting the extracted list.

If you drop the sorting (which is not needed unless you're comparing the list), it gets down to 12,339 microseconds.

But really, you don't need to return the keys anyway. Looking at the holistic isValidTimezoneId(), you'd be better off doing this:

function isValidTimezoneId2($tzid)
{
$valid = array();
$tza = timezone_abbreviations_list();
foreach ($tza as $zone)
{
foreach ($zone as $item)
{
$valid[$item['timezone_id']] = true;
}
}
unset($valid['']);
return !!$valid[$tzid];
}

That is, assuming you only need to test once per execution, otherwise you'd want to save $valid after the first run. This approach avoids having to do a sort or converting the keys to values, key lookups are faster than in_array() searches and there's no extra function call. Setting the array values to true instead of 1 also removes a single cast when the result is true.

This brings it reliably down to under 12ms on my test machine, almost half the time of your example. A fun experiment in micro-optimizations!

JavaScript check if timezone name valid or not

In environments that fully support IANA time zone identifiers in ECMA-402 (ECMAScript Internationalization API), you can try using a time zone in a DateTimeFormat (or in the options of to toLocaleString) and it will throw an exception if it is not a valid time zone. You can use this to test for validity, but only in environments where it is supported.

function isValidTimeZone(tz) {
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('Time zones are not available in this environment');
}

try {
Intl.DateTimeFormat(undefined, {timeZone: tz});
return true;
}
catch (ex) {
return false;
}
}

// Usage:
isValidTimeZone('America/Los_Angeles') // true
isValidTimeZone('Foo/Bar') // false

If you cannot be assured of your environment, then the best way would be with moment-timezone

!!moment.tz.zone('America/Los_Angeles') // true
!!moment.tz.zone('Foo/Bar') // false

Of course, you could always extract your own array of time zone names (perhaps with moment.tz.names() and test against that.

TimeZone validation in Java

You can get all supported ID using getAvailableIDs()

Then loop the supportedID array and compare with your String.

Example:

String[] validIDs = TimeZone.getAvailableIDs();
for (String str : validIDs) {
if (str != null && str.equals("yourString")) {
System.out.println("Valid ID");
}
}

Detect timezone abbreviation using JavaScript

If all else fails, you can simply create your own hashtable with the long names and abbreviations.

List of Timezone IDs for use with FindTimeZoneById() in C#?

Here's a full listing of a program and its results.

The code:

using System;

namespace TimeZoneIds
{
class Program
{
static void Main(string[] args)
{
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
{
// For a Console App
Console.WriteLine(z.Id + "," + z.BaseUtcOffset + "," + z.StandardName + "," + z.DisplayName + "," + z.DaylightName);
// For any other App
System.Diagnostics.Debug.WriteLine(z.Id + "," + z.BaseUtcOffset + "," + z.StandardName + "," + z.DisplayName + "," + z.DaylightName);
}
}
}
}

Results can change over time:

Sample Image

PHP Timezone List

Take my array of time zones, which I made specially for select element. It is associated array where key is PHP time zone and value is human representation. This is it:

$timezones = array(
'Pacific/Midway' => "(GMT-11:00) Midway Island",
'US/Samoa' => "(GMT-11:00) Samoa",
'US/Hawaii' => "(GMT-10:00) Hawaii",
'US/Alaska' => "(GMT-09:00) Alaska",
'US/Pacific' => "(GMT-08:00) Pacific Time (US & Canada)",
'America/Tijuana' => "(GMT-08:00) Tijuana",
'US/Arizona' => "(GMT-07:00) Arizona",
'US/Mountain' => "(GMT-07:00) Mountain Time (US & Canada)",
'America/Chihuahua' => "(GMT-07:00) Chihuahua",
'America/Mazatlan' => "(GMT-07:00) Mazatlan",
'America/Mexico_City' => "(GMT-06:00) Mexico City",
'America/Monterrey' => "(GMT-06:00) Monterrey",
'Canada/Saskatchewan' => "(GMT-06:00) Saskatchewan",
'US/Central' => "(GMT-06:00) Central Time (US & Canada)",
'US/Eastern' => "(GMT-05:00) Eastern Time (US & Canada)",
'US/East-Indiana' => "(GMT-05:00) Indiana (East)",
'America/Bogota' => "(GMT-05:00) Bogota",
'America/Lima' => "(GMT-05:00) Lima",
'America/Caracas' => "(GMT-04:30) Caracas",
'Canada/Atlantic' => "(GMT-04:00) Atlantic Time (Canada)",
'America/La_Paz' => "(GMT-04:00) La Paz",
'America/Santiago' => "(GMT-04:00) Santiago",
'Canada/Newfoundland' => "(GMT-03:30) Newfoundland",
'America/Buenos_Aires' => "(GMT-03:00) Buenos Aires",
'Greenland' => "(GMT-03:00) Greenland",
'Atlantic/Stanley' => "(GMT-02:00) Stanley",
'Atlantic/Azores' => "(GMT-01:00) Azores",
'Atlantic/Cape_Verde' => "(GMT-01:00) Cape Verde Is.",
'Africa/Casablanca' => "(GMT) Casablanca",
'Europe/Dublin' => "(GMT) Dublin",
'Europe/Lisbon' => "(GMT) Lisbon",
'Europe/London' => "(GMT) London",
'Africa/Monrovia' => "(GMT) Monrovia",
'Europe/Amsterdam' => "(GMT+01:00) Amsterdam",
'Europe/Belgrade' => "(GMT+01:00) Belgrade",
'Europe/Berlin' => "(GMT+01:00) Berlin",
'Europe/Bratislava' => "(GMT+01:00) Bratislava",
'Europe/Brussels' => "(GMT+01:00) Brussels",
'Europe/Budapest' => "(GMT+01:00) Budapest",
'Europe/Copenhagen' => "(GMT+01:00) Copenhagen",
'Europe/Ljubljana' => "(GMT+01:00) Ljubljana",
'Europe/Madrid' => "(GMT+01:00) Madrid",
'Europe/Paris' => "(GMT+01:00) Paris",
'Europe/Prague' => "(GMT+01:00) Prague",
'Europe/Rome' => "(GMT+01:00) Rome",
'Europe/Sarajevo' => "(GMT+01:00) Sarajevo",
'Europe/Skopje' => "(GMT+01:00) Skopje",
'Europe/Stockholm' => "(GMT+01:00) Stockholm",
'Europe/Vienna' => "(GMT+01:00) Vienna",
'Europe/Warsaw' => "(GMT+01:00) Warsaw",
'Europe/Zagreb' => "(GMT+01:00) Zagreb",
'Europe/Athens' => "(GMT+02:00) Athens",
'Europe/Bucharest' => "(GMT+02:00) Bucharest",
'Africa/Cairo' => "(GMT+02:00) Cairo",
'Africa/Harare' => "(GMT+02:00) Harare",
'Europe/Helsinki' => "(GMT+02:00) Helsinki",
'Europe/Istanbul' => "(GMT+02:00) Istanbul",
'Asia/Jerusalem' => "(GMT+02:00) Jerusalem",
'Europe/Kiev' => "(GMT+02:00) Kyiv",
'Europe/Minsk' => "(GMT+02:00) Minsk",
'Europe/Riga' => "(GMT+02:00) Riga",
'Europe/Sofia' => "(GMT+02:00) Sofia",
'Europe/Tallinn' => "(GMT+02:00) Tallinn",
'Europe/Vilnius' => "(GMT+02:00) Vilnius",
'Asia/Baghdad' => "(GMT+03:00) Baghdad",
'Asia/Kuwait' => "(GMT+03:00) Kuwait",
'Africa/Nairobi' => "(GMT+03:00) Nairobi",
'Asia/Riyadh' => "(GMT+03:00) Riyadh",
'Europe/Moscow' => "(GMT+03:00) Moscow",
'Asia/Tehran' => "(GMT+03:30) Tehran",
'Asia/Baku' => "(GMT+04:00) Baku",
'Europe/Volgograd' => "(GMT+04:00) Volgograd",
'Asia/Muscat' => "(GMT+04:00) Muscat",
'Asia/Tbilisi' => "(GMT+04:00) Tbilisi",
'Asia/Yerevan' => "(GMT+04:00) Yerevan",
'Asia/Kabul' => "(GMT+04:30) Kabul",
'Asia/Karachi' => "(GMT+05:00) Karachi",
'Asia/Tashkent' => "(GMT+05:00) Tashkent",
'Asia/Kolkata' => "(GMT+05:30) Kolkata",
'Asia/Kathmandu' => "(GMT+05:45) Kathmandu",
'Asia/Yekaterinburg' => "(GMT+06:00) Ekaterinburg",
'Asia/Almaty' => "(GMT+06:00) Almaty",
'Asia/Dhaka' => "(GMT+06:00) Dhaka",
'Asia/Novosibirsk' => "(GMT+07:00) Novosibirsk",
'Asia/Bangkok' => "(GMT+07:00) Bangkok",
'Asia/Jakarta' => "(GMT+07:00) Jakarta",
'Asia/Krasnoyarsk' => "(GMT+08:00) Krasnoyarsk",
'Asia/Chongqing' => "(GMT+08:00) Chongqing",
'Asia/Hong_Kong' => "(GMT+08:00) Hong Kong",
'Asia/Kuala_Lumpur' => "(GMT+08:00) Kuala Lumpur",
'Australia/Perth' => "(GMT+08:00) Perth",
'Asia/Singapore' => "(GMT+08:00) Singapore",
'Asia/Taipei' => "(GMT+08:00) Taipei",
'Asia/Ulaanbaatar' => "(GMT+08:00) Ulaan Bataar",
'Asia/Urumqi' => "(GMT+08:00) Urumqi",
'Asia/Irkutsk' => "(GMT+09:00) Irkutsk",
'Asia/Seoul' => "(GMT+09:00) Seoul",
'Asia/Tokyo' => "(GMT+09:00) Tokyo",
'Australia/Adelaide' => "(GMT+09:30) Adelaide",
'Australia/Darwin' => "(GMT+09:30) Darwin",
'Asia/Yakutsk' => "(GMT+10:00) Yakutsk",
'Australia/Brisbane' => "(GMT+10:00) Brisbane",
'Australia/Canberra' => "(GMT+10:00) Canberra",
'Pacific/Guam' => "(GMT+10:00) Guam",
'Australia/Hobart' => "(GMT+10:00) Hobart",
'Australia/Melbourne' => "(GMT+10:00) Melbourne",
'Pacific/Port_Moresby' => "(GMT+10:00) Port Moresby",
'Australia/Sydney' => "(GMT+10:00) Sydney",
'Asia/Vladivostok' => "(GMT+11:00) Vladivostok",
'Asia/Magadan' => "(GMT+12:00) Magadan",
'Pacific/Auckland' => "(GMT+12:00) Auckland",
'Pacific/Fiji' => "(GMT+12:00) Fiji",
);

How to get timezone from airport code (IATA/FAA)

I've managed to find a solution to the issue. Through the flightstats.com API it is possible to get a free but limited access to a complete airport database: https://developer.flightstats.com/api-docs/airports/v1

The API returns all active/inactive airports in the following format:

{
"fs": "LAX",
"iata": "LAX",
"icao": "KLAX",
"faa": "LAX",
"name": "Los Angeles International Airport",
"street1": "One World Way",
"street2": "",
"city": "Los Angeles",
"cityCode": "LAX",
"stateCode": "CA",
"postalCode": "90045-5803",
"countryCode": "US",
"countryName": "United States",
"regionName": "North America",
"timeZoneRegionName": "America/Los_Angeles",
"weatherZone": "CAZ041",
"localTime": "2014-06-20T06:00:50.439",
"utcOffsetHours": -7,
"latitude": 33.943399,
"longitude": -118.408279,
"elevationFeet": 126,
"classification": 1,
"active": true,
"delayIndexUrl": "https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/LAX?codeType=fs",
"weatherUrl": "https://api.flightstats.com/flex/weather/rest/v1/json/all/LAX?codeType=fs"
}

This was exactly the data I needed to be able to make my function:

echo getTimezoneFromAirportCode("LAX"); // -7

The data is available through the following GET request:

https://api.flightstats.com/flex/airports/rest/v1/json/all?appId=[appId]&appKey=[appKey]

[appId] and [appKey] will be provided after creating a free flightstats.com developer account here: https://developer.flightstats.com/signup

How can I determine a timezone by the UTC offset?

Short answer: you can't.

Daylight saving time make it impossible. For example, there is no way to determine, solely from UTC offset, the difference between Arizona and California in the summer, or Arizona and New Mexico in the winter (since Arizona does not observe DST).

There is also the issue of what time different countries observe DST. For example, in the US DST starts earlier and ends later than in Europe.

A close guess is possible (i.e. +/- an hour), but if you are using it to display time to users you will inevitably display the wrong time to some of them.


Update: From the comments, it looks like your primary goal is to display a timestamp in the user's local timezone. If that is what you want to do, you should send the time as a UTC timestamp, and then just rewrite it on the user's browser with Javascript. In the case that they don't have Javascript enabled, they would still see a usable UTC timestamp. Here is a function I came up with in this question, which I used in this Greasemonkey script. You may want to tweak it to suit your needs.

//@param timestamp An ISO-8601 timestamp in the form YYYY-MM-DDTHH:MM:SS±HH:MM
//Note: Some other valid ISO-8601 timestamps are not accepted by this function
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;

return new Date(
Date.UTC(
parseInt(matches[1], 10),
parseInt(matches[2], 10) - 1,
parseInt(matches[3], 10),
parseInt(matches[4], 10),
parseInt(matches[5], 10),
parseInt(matches[6], 10)
) - offset*60*1000
);
}
return null;
}

Here is a function I use on my blog to display a parsed timestamp in the user's local timezone. Again, you can tweak it to the format you want.

var weekDays = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday");
var months = new Array("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");

function toLocalTime(date)
{
var hour = date.getHours();
var ampm = (hour < 12 ? "am" : "pm");
hour = (hour + 11)%12 + 1;

var minutes = date.getMinutes();
if(minutes < 10)
minutes = "0" + minutes;

return weekDays[date.getDay()] + ", "
+ months[date.getMonth()] + " "
+ date.getDate() + ", "
+ date.getFullYear() + " at "
+ hour + ":"
+ minutes + " "
+ ampm;
}

How to get a user's time zone?

edit/update:

Xcode 8 or later • Swift 3 or later

var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT // -7200

if you need the abbreviation:

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation // "GMT-2"

if you need the timezone identifier:

var localTimeZoneIdentifier: String { return TimeZone.current.identifier }

localTimeZoneIdentifier // "America/Sao_Paulo"

To know all timezones abbreviations available:

var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]

To know all timezones names (identifiers) available:

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]

There is a few other info you may need:

var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)

var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset) // 3600 seconds (1 hour - daylight savings time)

var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition } // "Feb 18, 2017, 11:00 PM"
print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"

var nextDaylightSavingTimeTransitionAfterNext: Date? {
guard
let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
else { return nil }
return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}

nextDaylightSavingTimeTransitionAfterNext // "Oct 15, 2017, 1:00 AM"

TimeZone - Apple Developer Swift Documentation



Related Topics



Leave a reply



Submit