如何获取TimeZoneInfo的简称

Kum*_*mar 13 .net c# vb.net datetime date

有没有任何方法可以从System.TimeZoneInfo.Local获取3个char代码?

例如EDT而不是东部夏令时等.

Rob*_*les 9

不幸的是,我知道没有简单的内置方法.但是,你可以自己把东西放在一起.这是一个例子:

public static class TimeZoneInfoExtensions {

        public static string Abbreviation(this TimeZoneInfo Source) {

        var Map = new Dictionary<string, string>()
        {
            {"eastern standard time","est"},
            {"mountain standard time","mst"},
            {"central standard time","cst"},
            {"pacific standard time","pst"}
            //etc...
        };

        return Map[Source.Id.ToLower()].ToUpper();

    }

}
Run Code Online (Sandbox Code Playgroud)

使用方法如下:

string CurrentTimeZoneAbbreviation = System.TimeZoneInfo.Local.Abbreviation();
Run Code Online (Sandbox Code Playgroud)

如果您需要更多转换,只需将它们插入Map字典即可.

TimeZoneInfo.Id将是与[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones]中的给定键匹配的字符串.如果您可以在线找到匹配的数据库,包含相同的ID和缩写,则可以快速提取和导入对(例如,使用正则表达式)并将其放入Map字典中.