2010-05-23 65 views

回答

2
DateTime dt = DateTime.ParseExact(s,"ddd MMM dd HH:mm:ss UTCzzzz yyyy", System.Globalization.CultureInfo.InvariantCulture); 
+0

太棒了!像魅力一样工作。以正确方式指示时区的zzzz。在我的尝试中,我将时区字面翻译为“UTC + 0300”,如果将应用程序部署到具有不同时区的另一个地方,该时区肯定会中断。谢谢johncatfish! – Galilyou 2010-05-24 10:31:53

0

对不起,我以前的答案很简单。 用日期格式中的MMM替换MM,它应该没问题。

+0

哦,是的,当然:)我的意思是,当然,但问题是自定义格式。 DateTime.Parse(“SSun 5月23日22:00:00 UTC + 0300 2010”);将通过一个FormatException。所以! – Galilyou 2010-05-23 17:02:01

+0

这不会工作,它不是一个标准格式。 – Nix 2010-05-23 17:02:12

1

这不是标准的.NET格式,所以你可能需要手动解析它。 UTC+0300位表示时区,其他所有内容都是日期和时间的一部分。

2

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

 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); 
1

找到我试图通过@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); 
}