Timezone Abbreviations

前端 未结 7 1524
情话喂你
情话喂你 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:18

    I store all my dates in UTC and often have to display them in local time, so I created an extension method ToAbbreviation()

        public static string ToAbbreviation(this TimeZone theTimeZone)
        {
    
            string timeZoneString = theTimeZone.StandardName;
            string result = string.Concat(System.Text.RegularExpressions.Regex
               .Matches(timeZoneString, "[A-Z]")
               .OfType()
               .Select(match => match.Value));
    
            return result;
        }
    

    example usage:

    string tz = TimeZone.CurrentTimeZone.ToAbbreviation();
    string formattedDate = String.Format("{0:yyyy/MM/dd hh:mm:ss} {1}", myDate, tz);
    

    Or, if you want to just get a formatted date string from a DateTime object:

    public static string ToLocalTimeWithTimeZoneAbbreviation(this DateTime dt)
    {
        DateTime localtime = dt.ToLocalTime();
        string tz = TimeZone.CurrentTimeZone.ToAbbreviation();
    
        string formattedDate = String.Format("{0:yyyy/MM/dd hh:mm:ss} {1}", localtime, tz);
        return formattedDate;
    }
    

    and use as follows:

    string formattedDate = myDateTimeObject.ToLocalTimeWithTimeZoneAbbreviation()
    

    output: 2019-06-24 02:26:31 EST

提交回复
热议问题