【问题标题】:Translate ISO 8601 UTC time format to hh:mm of EST将 ISO 8601 UTC 时间格式转换为 EST 的 hh:mm
【发布时间】:2016-08-22 16:08:37
【问题描述】:

我有一个对象列表,这些对象是从 json 字符串中反序列化的,其中包含以 UTC 时间表示的开始/结束时间字段。例如:“2016-08-22T15:30:00Z”(美国东部时间上午 11:30)。在以 JSON 格式发送列表以显示在网页上之前,我需要在服务器上将时间转换为用户友好的格式(例如,“11:30 AM”)。是否有一个 c# 函数可以帮助我将时间属性转换为所需的结果?

代码示例:

    public class Event
    {
        public int EventId { get; set; } //1
        public string Name { get; set; } //Karate class
        public string StartAt { get; set; } //2016-08-22T15:30:00Z
        public string EndAt { get; set; } //2016-08-22T16:30:00Z
    }

    public class Events
    {
        public List<Event> Events {get; set;}

    }

    //de-serialize from json string
    string eventsForToday = "{}" //some json string from api
    var eventList = (Events)JsonConvert.DeserializeObject(eventsForToday, typeof(Events));

    foreach (var item in eventList.Events)
    {
        //needs to be 11:30AM instead of 2016-08-22T15:30:00Z
        Console.WriteLine (item.StartAt) 
    }

我知道逻辑是无论 UTC 时间是什么,它都应该偏移 4(或 5,具体取决于一年中的时间)。但是修改对象最直接的方法是什么?有没有办法投影一个格式改变的新列表等?

【问题讨论】:

    标签: c# json datetime linq-to-objects utc


    【解决方案1】:

    您可以将每个字符串转换为日期时间。 DateTime 有一个 ToLocalTime() 方法,只要您指定 DateTime 的 Kind 属性,它就会为您进行转换。例如,

    foreach (var item in eventList.Events)
    {
        DateTime timeUtc = DateTime.SpecifyKind(DateTime.Parse(item.StartAt), DateTimeKind.Utc);
        Console.WriteLine (timeUtc.ToLocalTime()); //Add .ToShortTimeString() if you just want the time (and not the date)
    }
    

    但是,由于您的字符串有一个尾随“Z”,您应该可以使用Convert.ToDateTime(item.StartAt).ToWhateverString()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 2023-03-15
      • 2011-05-02
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2020-11-23
      相关资源
      最近更新 更多