C# 中获取时区列表

时间:2024-07-04 16:37:26
  • c#中获取时区列表 下面方法获得的仅仅用来显示和使用,无法用来进行时间转换。
 public static List<DisplayTimeZone> GetSystemTimeZones()
{
List<DisplayTimeZone> list = new List<DisplayTimeZone>(); PermissionSet set = new PermissionSet(PermissionState.None);
set.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"));
set.Assert();
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones", RegistryKeyPermissionCheck.Default, RegistryRights.ExecuteKey))
{
if (key != null)
{
foreach (string str in key.GetSubKeyNames())
{
DisplayTimeZone timeZone = null;
Exception e = null;
TryGetTimeZone(str, out timeZone, out e);
if (timeZone != null)
{
list.Add(timeZone);
}
}
}
}
return list;
} private static void TryGetTimeZone(string id, out DisplayTimeZone value, out Exception e)
{
e = null;
value = new DisplayTimeZone();
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", new object[] { @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones", id }), RegistryKeyPermissionCheck.Default, RegistryRights.ExecuteKey))
{
value.DisplayName = key.GetValue("Display", string.Empty, RegistryValueOptions.None) as string;
value.StandardName = key.GetValue("Std", string.Empty, RegistryValueOptions.None) as string;
value.DaylightName = key.GetValue("Dlt", string.Empty, RegistryValueOptions.None) as string;
}
}
catch (Exception ex)
{
e = ex;
value = null;
}
} public class DisplayTimeZone
{
public string StandardName;
public string DisplayName;
public string DaylightName;
}