Can you find TimeZoneById with TimeZoneDisplayName?

I am using asp.net mvc and I am using the method that was on this site.

How to list all timezones in .NET?

So this is what I do. Then I display the results to the user. The user selects their timezone and I have stored the display name in the database.

However, I am now trying to make a timezone change.

I'm trying to do it like this (I'm not sure if this is the correct way to do it though).

  TimeZoneInfo zoneInfo  = TimeZoneInfo.FindSystemTimeZoneById(id);
  var time = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now, zoneInfo);

      

So I think it would be correct when it gets the system time and timezone of the users and uses that information to convert it to local UTC time.

So, assuming everything is ok, what I did (if don't correct me) the problem I am facing is how do I get the id?

I don't know how to find the ID. For example, I want to store the ID instead of DisplayName in the database, but I don't know how to determine the ID from DisplayName.

thank

+2


source to share


2 answers


Perhaps cache them when run in a dictionary:

static readonly Dictionary<string, TimeZoneInfo> zones
    = TimeZoneInfo.GetSystemTimeZones().ToDictionary(z => z.DisplayName);

      



Then choose zones[displayName]

(or via zones.TryGetValue(displayName, out zone)

if you want to be safe).

+4


source


If you are using LINQ you can do this:



var tz = "(UTC-06:00) Central Time (US & Canada)";
var tzi = TimeZoneInfo.GetSystemTimeZones().Single (t => t.DisplayName == tz);
Console.WriteLine("Id: {0} | DisplayName: {1} | SupportsDaylightSavingTime: {2}"
    , tzi.Id, tzi.DisplayName, tzi.SupportsDaylightSavingTime);

      

+1


source







All Articles