How to display DateTime with an abbreviated Time Zone?

前端 未结 8 913
长情又很酷
长情又很酷 2020-12-08 19:02

I am aware of the System.TimeZone class as well as the many uses of the DateTime.ToString() method. What I haven\'t been able to find is a way to convert a DateTime to a st

相关标签:
8条回答
  • 2020-12-08 19:40

    If pulling the abbreviation from the DaylightName/StandardName, you're going to be better off building the string using a StringBuilder, for strings are immutable.

        public static string ToCurrentTimeZoneString(this DateTime date)
        {
            string name = TimeZone.CurrentTimeZone.IsDaylightSavingTime(date) ?
                TimeZone.CurrentTimeZone.DaylightName :
                TimeZone.CurrentTimeZone.StandardName;
            return name;
        }
    
        public static string ToCurrentTimeZoneShortString(this DateTime date)
        {
            StringBuilder result = new StringBuilder();
    
            foreach (string value in date.ToCurrentTimeZoneString().Split(' '))
            {
                if (value.IsNotNullOrEmptyWithTrim())
                {
                    result.Append(char.ToUpper(value[0]));
                }
            }
    
            return result.ToString();
        }
    

    Of course, an array containing KeyValuePair's is probably best for a multinational company. If you want to shave a few minutes off of a tight deadline, and you are at a US company, this works.

    0 讨论(0)
  • 2020-12-08 19:40

    Ok, It's been 4 years (and almost a week), it's time we brought LINQ into the discussion...

    Putting together Criag's and Bob's ideas...

    public static String TimeZoneName2(DateTime dt)
    {
        var return ToCurrentTimeZoneShortString(dt)
                     .Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
        return sSplit.Aggregate("", (st,w)=> st +=w[0]);
    }
    

    Unless you can trust TimeZone to never return a string with two consecutive spaces:

    public static String TimeZoneName3(DateTime dt)
    {
        return ToCurrentTimeZoneShortString(dt).Split(' ')
                     .Aggregate("", (st,w)=> st +=w[0]);
    }
    
    0 讨论(0)
提交回复
热议问题