代码之家  ›  专栏  ›  技术社区  ›  Ahmed

如何以这种格式分析日期时间?“5月23日周日22:00:00 UTC+0300 2010”

  •  1
  • Ahmed  · 技术社区  · 15 年前

    这是一个快速的,我想分析一个日期,格式是“Sun May 23 22:00:00 UTC+0300 2010”
    这是有效的UTC日期时间吗?如何解析它?我试过:

    DateTime newStartTime = DateTime.ParseExact(hdnNewStartTime.Value, "ddd MM dd HH:mm:ss UTC+0300 yyyy", CultureInfo.CurrentCulture);
    

    但是,这不起作用,任何帮助感谢!

    6 回复  |  直到 15 年前
        1
  •  2
  •   user347594    15 年前
    DateTime dt = DateTime.ParseExact(s,"ddd MMM dd HH:mm:ss UTCzzzz yyyy", System.Globalization.CultureInfo.InvariantCulture);
    
        2
  •  2
  •   Nix    15 年前

    它不是标准格式,但您仍然可以解析它。

            string format = "ddd mmm dd HH:mm:ss zzzzz yyyy";
            string temp = "Sun May 23 22:00:00 UTC+0300 2010";
            DateTime time = DateTime.ParseExact(temp, format, CultureInfo.InvariantCulture);
    
        3
  •  1
  •   Donnie    15 年前

    这不是标准的.NET格式,因此您可能需要手动解析它。这个 UTC+0300 位表示时区,其他一切都是日期和时间的一部分。

        4
  •  1
  •   Blake Ramsdell    15 年前

    我尝试了@johncatfish提供的解决方案,它实现了我的预期。我假设你真的想保留时区信息。

    [Test()]
    public void TestCaseWorks ()
    {
        string format = "ddd MMM dd HH:mm:ss UTCzzzzz yyyy";
        string temp = "Sun May 23 22:00:00 UTC+0300 2010";
        DateTime time = DateTime.ParseExact(temp, format, CultureInfo.InvariantCulture);
    
        Assert.AreEqual(DayOfWeek.Sunday, time.DayOfWeek);
        Assert.AreEqual(5, time.Month);
        Assert.AreEqual(23, time.Day);
        Assert.AreEqual(0, time.Minute);
        Assert.AreEqual(0, time.Second);
        Assert.AreEqual(2010, time.Year);
    
        // Below is the only actually useful assert -- making sure the
        // timezone was parsed correctly.
    
        // In my case, I am GMT-0700, the target time is GMT+0300 so
        // 22 + (-7 - +3) = 12 is the expected answer. It is an exercise
        // for the reader to make a robust test that will work in any
        // timezone ;).
    
        Assert.AreEqual(12, time.Hour);
    }
    
        5
  •  0
  •   Julien Lebosquain    15 年前

    很抱歉我之前的回答太简单了。 以日期格式将mm替换为mmm,应该可以。

        6
  •  0
  •   ICR    15 年前

    从给出的示例中,无法判断月份应为3个字母的形式(一月、二月、五月等)还是完整的形式(一月、二月、五月等)。

    如果应该是短格式,请使用:

    ddd MMM dd HH : mm : ss UTC zzz yyyy

    如果是长形的,使用:

    滴滴涕 MMMM DD HH : 毫米 : SS UTC ZZZ 年份

    有关可用格式说明符的详细信息,请访问 http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx