【问题标题】:Find time zone and time from given string of timestamp从给定的时间戳字符串中查找时区和时间
【发布时间】:2013-09-22 09:18:18
【问题描述】:

我需要解析时间戳并从如下字符串中获取时间和时区,

时间戳 = "2013-09-17T14:55:00.355-08:00"

从上面的字符串中,我应该能够获得下午 2:55 的时间和东部标准时间(东部)的时区

谁能告诉我上面的解析是怎么做的。

【问题讨论】:

    标签: c# .net datetime timezone timestamp


    【解决方案1】:

    您可以使用DateTimeOffset.ParseExact 获得DateTimeOffset,其中包含本地时间和与UTC 的偏移量。但是,当时可能有多个时区与 UTC 有相同的偏移量,因此您无法获得实际的时区。

    示例代码:

    using System;
    using System.Globalization;
    
    class Test
    {
        static void Main()        
        {
            string text = "2013-09-17T14:55:00.355-08:00";
            DateTimeOffset dto = DateTimeOffset.ParseExact(text,
                "yyyy-MM-dd'T'HH:mm:ss.fffzzz",
                CultureInfo.InvariantCulture);
            Console.WriteLine(dto);
        }
    } 
    

    或者使用我的Noda Time 库:

    using System;
    using NodaTime;
    using NodaTime.Text;
    
    class Test
    {
        static void Main()        
        {
            string text = "2013-09-17T14:55:00.355-08:00";
            // Use GeneralIsoPattern just to get a default culture/template value
            OffsetDateTime odt = OffsetDateTimePattern.GeneralIsoPattern
                .WithPatternText("yyyy-MM-dd'T'HH:mm:ss.fffo<+HH:mm>")
                .Parse(text)
                .Value;
            Console.WriteLine(odt);
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      相关资源
      最近更新 更多