0

I am trying to convert an integer value to the timezone name it corresponds to. For instance: -6 would return either Central Standard Time or CST. I have looked at the TimeZoneInfo object but this appears to be able to only give me the local time zone or the integer value it corresponds with.

Clarification

I have an integer value, I do not know what the time zone is. I also do not care what time zone my server is running in. I need to take an integer value and get the Time Zone name.

Prior to Deprecation you could get the name of the timezone by:

    // Get current time zone.
    TimeZone zone = TimeZone.CurrentTimeZone;
    string standard = zone.StandardName;
    string daylight = zone.DaylightName;
    Console.WriteLine(standard);
    Console.WriteLine(daylight);

This would give you:

Mountain Standard Time

Mountain Daylight Time

I am looking for a solution like this where I have the offset and get the name in return.

Community
  • 1
  • 1
Robert
  • 4,306
  • 11
  • 45
  • 95
  • You could get _a_ TZ from an offset. – H H Nov 14 '19 at 16:47
  • 1
    Possible duplicate of this? https://stackoverflow.com/questions/1274743/how-can-i-determine-a-timezone-by-the-utc-offset – Ross Gurbutt Nov 14 '19 at 16:54
  • Does this answer your question? [.NET Get timezone offset by timezone name](https://stackoverflow.com/questions/2979524/net-get-timezone-offset-by-timezone-name) – haldo Nov 14 '19 at 17:01
  • 1
    What would +8 return? Australian Western Standard Time or China Standard Time or something else? – Sweeper Nov 14 '19 at 17:08
  • Does this answer your question? [How can I determine a timezone by the UTC offset?](https://stackoverflow.com/questions/1274743/how-can-i-determine-a-timezone-by-the-utc-offset) – omajid Nov 14 '19 at 17:30
  • @sweeper What ever the name common name is. It doesn't matter as long as I get a value back. – Robert Nov 14 '19 at 18:29

2 Answers2

2

I figured out how to get the information I need:

    [Fact]
    public void GetTimeZoneNameByOffsetTime_ShouldParseTimeZoneNameFromOffsetTime()
    {
        //Arrange
        var expected = "Central America Standard Time";

        //Act
        var allTimeZones = TimeZoneInfo.GetSystemTimeZones();
        var newTimeZone = allTimeZones.FirstOrDefault(x => x.BaseUtcOffset == new TimeSpan(-6, 0, 0));
        var actual = newTimeZone.StandardName;

        //Assert
        actual.ShouldBe(expected);
    }
Robert
  • 4,306
  • 11
  • 45
  • 95
  • This approach could be ambiguous because there are multiple time zones with BaseUtcOffset = -6, and completely incorrect because of the day light savings time. For example in the US, -5 in Summer is CDT (Central Daylight Time) and in Winter it's EST (Eastern Standard Time). – Oleg Aug 09 '23 at 04:18