Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get TimeZoneInfo short name

Is there any method to get the 3 char code from System.TimeZoneInfo.Local ?

e.g. EDT instead of Eastern Daylight time etc.

like image 338
Kumar Avatar asked Sep 09 '09 22:09

Kumar


People also ask

How to get short TimeZone from javascript?

Use the toLocaleDateString method to get the time zone abbreviation. The method can be passed an options object where the timeZoneName property can be set to short to get the time zone abbreviation. Copied! // 👇️ GMT+2 (with locale en-US) console.


2 Answers

Unfortunately, there is no easy built-in way of doing this that I know of. However, you could put something together yourself. Here's an example:

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();

    }

}

Use as follows:

string CurrentTimeZoneAbbreviation = System.TimeZoneInfo.Local.Abbreviation();

If you need more conversions you could just plug them into the Map dictionary.

TimeZoneInfo.Id will be a string matching a given key in [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones]. If you can find a matching database online, containing the same Ids as well as the abbreviations, it would be possible to quickly extract and import the pairs (with regular expressions, for example) and drop those into the Map dictionary.

like image 173
Robert Venables Avatar answered Nov 02 '22 09:11

Robert Venables


You can write something like:

var abbr = System.TimeZoneInfo.Local.TimeZoneAbbr();

And the helper for it:

public static class ConvertionHelper
{
    public static String TimeZoneAbbr(this TimeZoneInfo zone)
    {
        var zoneName = zone.Id;/* zone.IsDaylightSavingTime(DateTime.UtcNow)
            ? zone.DaylightName
            : zone.StandardName;*/
        var zoneAbbr = zoneName.CapitalLetters();
        return zoneAbbr;
    }

    public static String CapitalLetters(this String str)
    {
        return str.Transform(c => Char.IsUpper(c)
            ? c.ToString(CultureInfo.InvariantCulture)
            : null);
    }

    private static String Transform(this String src, Func<Char, String> transformation)
    {
        if (String.IsNullOrWhiteSpace(src))
        {
            return src;
        }

        var result = src.Select(transformation)
            .Where(res => res != null)
            .ToList();

        return String.Join("", result);
    }
}
like image 32
Oleg Avatar answered Nov 02 '22 08:11

Oleg