Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a string a valid timezone in .Net

Tags:

timezone

c#

I receive a string as a json parameter and it's supposed to be a timezone ID. I want to check for that.

This is what I have:

TheTimezoneID = TheTimezoneID.Trim();
var AllTimezones = TimeZoneInfo.GetSystemTimeZones();

if (TheTimezoneID "is a valid .net timezone" == true) {}

What's the linq expression that'll test if TheTimezoneID is in AllTimezones? I tried using .Any but it's not working.

Thanks.

like image 703
frenchie Avatar asked Dec 28 '22 04:12

frenchie


1 Answers

If you're going to do this in various situations you should probably use:

private static readonly HashSet<string> AllTimeZoneIds = 
    new HashSet<string>(TimeZoneInfo.GetSystemTimeZones()
                                    .Select(tz => tz.Id));

Then you can just use:

if (AllTimeZoneIds.Contains(timeZoneId))

There's no need to use LINQ to iterate over the whole time zone list on each time when a hash set can just perform an O(1) lookup.

If you're just curious about using Any, it would be:

if (AllTimeZoneIds.Select(tz => tz.Id).Contains(timeZoneid))

or

if (AllTimeZoneIds.Any(tz => tz.Id == timeZoneid))

Note that "time zone ID" is a pretty woolly concept. This will check if it's a valid .NET time zone ID. If you're actually getting time zones like "Europe/London", that's a different matter.

like image 88
Jon Skeet Avatar answered Jan 13 '23 16:01

Jon Skeet