How to parse DateTime in this format? "Sun May 23 22:00:00 UTC+0300 2010"
This is a quick one, i wanna parse a date that comes in this format "Sun May 23 22:00:00 UTC+0300 2010"
Is this a valid UTC DateTime? And how to parse it? I tried :DateTime newS开发者_JAVA百科tartTime = DateTime.ParseExact(hdnNewStartTime.Value, "ddd MM dd HH:mm:ss UTC+0300 yyyy", CultureInfo.CurrentCulture);
However, this didn't work, any help appreciated!
DateTime dt = DateTime.ParseExact(s,"ddd MMM dd HH:mm:ss UTCzzzz yyyy", System.Globalization.CultureInfo.InvariantCulture);
Its not a standard format, but you can still parse it.
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);
This isn't in a standard .NET format, so you'll probably have to parse it by hand. The UTC+0300
bit indicates the timezone, everything else is part of the date and time.
I tried the solution presented by @johncatfish and it does what I expect. I would presume that you actually want to keep the timezone information.
[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);
}
Sorry for my previous answer which was quite simplistic. Replace MM by MMM in your date format and it should be fine.
From the example given, it isn't possible to tell if the month should be in the 3 letter form (Jan, Feb, May etc.) or in the full form (January, February, May etc.).
If it should be in the short form, use:
ddd MMM dd HH:mm:ss UTCzzz yyyy
If it should be in the long form, use:
ddd MMMM dd HH:mm:ss UTCzzz yyyy
Details of the formatting specifiers available can be found at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
精彩评论