How do I enumerate all time zones in .NET?

前端 未结 4 1083
长发绾君心
长发绾君心 2020-12-05 02:58

I would like to have a list of all the time zones available on a Windows Machine. How can I do this in .NET?

I know about the TimeZoneInfo.GetSystemTimeZones method

4条回答
  •  青春惊慌失措
    2020-12-05 03:16

    If wanting a json output from a WebAPI call:

    using System;
    using System.Collections.Generic;
    
    namespace MyProject.ViewModels
    {
        public class TimeZoneViewModel
        {
            public readonly List CTimeZones;
    
            public TimeZoneViewModel()
            {
                CTimeZones = new List();
                foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
                {
                    var tz = new CTimeZone(z.Id, z.DisplayName, z.BaseUtcOffset);
                    CTimeZones.Add(tz);
                }
            }
    
        }
    
        public class CTimeZone
        {
            public string Id { get; set; }
            public string DisplayName { get; set; }
            public TimeSpan BaseUtcOffset { get; set; }
    
            public CTimeZone(string id, string displayName, TimeSpan utcOffset)
            {
                Id = id;
                DisplayName = displayName;
                BaseUtcOffset = utcOffset;
            }
        }
    }
    

    Then use it in WebAPI:

    [HttpGet("Api/TimeZones")]
    public JsonResult GetTimeZones()
    {
        return Json(new TimeZoneViewModel().CTimeZones);
    }
    

    Output:

    [{
        "id": "Dateline Standard Time",
        "displayName": "(UTC-12:00) International Date Line West",
        "baseUtcOffset": "-12:00:00"
      },
      {
        "id": "UTC-11",
        "displayName": "(UTC-11:00) Coordinated Universal Time-11",
        "baseUtcOffset": "-11:00:00"
      },
      {
        "id": "Aleutian Standard Time",
        "displayName": "(UTC-10:00) Aleutian Islands",
        "baseUtcOffset": "-10:00:00"
      },
      {
        "id": "Hawaiian Standard Time",
        "displayName": "(UTC-10:00) Hawaii",
        "baseUtcOffset": "-10:00:00"
      },...
    

提交回复
热议问题