If you’ve worked with timezones in Python, you’ve probably used pytz to get IANA timezone names for specific countries:
tz_names = pytz.country_timezones.get(country.upper(), [])
When I needed similar functionality in Delphi, I was surprised to find that there wasn’t a readily available library to get IANA timezone names for countries.
After searching without success, I decided to create my own solution:
https://github.com/optinsoft/CountryTimezone
Here’s a practical example that demonstrates how to get a random timezone name and its UTC offset for a given country:
uses CountryTimezone, TZDB;
type
TTimezoneAndOffset = record
name: String;
offset: Integer;
end;
function GetRandomTimezoneAndOffset(country: String): TTimezoneAndOffset;
var
LCTZDict: TCountryTimezoneDictionary;
LCTZList: TStringList;
tz: TBundledTimeZone;
begin
LCTZDict := TCountryTimezoneDictionary.Create();
LCTZList := TStringList.Create;
try
LCTZDict.GetCountryTimezones(country, LCTZList);
Result.name := LCTZList[Random(LCTZList.Count)];
tz := TBundledTimeZone.GetTimeZone(Result.name);
Result.offset := Trunc(tz.UtcOffset.TotalMinutes);
finally
LCTZList.Free;
LCTZDict.Free;
end;
end;
This function:
- Creates a country timezone dictionary
- Retrieves all timezone names for the specified country
- Selects a random timezone from the list
- Uses TZDB to get the UTC offset in minutes for that timezone