Timezone Abbreviations

前端 未结 7 1533
情话喂你
情话喂你 2020-11-28 08:07

TimeZoneInfo does not provide abbreviation or a short name for a given Timezone. The only good way to do it is to have a dictionary that will map abbreviations

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 08:41

    Your question does not indicate what time zones your application must operate within, but in my particular instance, I only have a need to be concerned with United States time zones and UTC.

    The abbreviations of U.S. time zones are always the first characters of each word in the time zone name. For instance, the abbreviation of "Mountain Standard Time" is "MST" and the abbreviation of "Eastern Daylight Time" is "EDT".

    If you have similar requirements, you can easily derive the time zone abbreviation of the local time zone from the local time zone's name directly, as follows (note: here I'm determining the proper name based on the current date and time):

    string timeZoneName = TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now)
                              ? TimeZone.CurrentTimeZone.DaylightName 
                              : TimeZone.CurrentTimeZone.StandardName;
    
    string timeZoneAbbrev = GetTzAbbreviation(timeZoneName);
    

    The code for the GetTzInitials() function is pretty straightforward. One thing worth mentioning is that some time zones may be set to Mexico or Canada, and the time zone names for these will come over with the country name in parenthesis, such as "Pacific Standard Time (Mexico)". To deal with this, any parenthesized data is passed back directly. The abbreviation returned for the above will be "PST(Mexico)", which works for me.

    string GetTzAbbreviation(string timeZoneName) {
        string output = string.Empty;
    
        string[] timeZoneWords = timeZoneName.Split(' ');
        foreach (string timeZoneWord in timeZoneWords) {
            if (timeZoneWord[0] != '(') {
                output += timeZoneWord[0];
            } else {
                output += timeZoneWord;
            }
        }
        return output;
    }
    

提交回复
热议问题