tags:

views:

410

answers:

2

I am trying to verify that a C# string is compliant with XML Schema dateTime format. Looking at the MSDN, it seems like "o", "s", or "u" standard format strings could all describe valid dateTimes, but I can't get DateTime.ParseExact to work for me. What am I doing wrong here?

string myDate = "1999-05-31T13:20:00.000-04:00";
DateTime.ParseExact(myDate, "o", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact(myDate, "s", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact(myDate, "u", CultureInfo.InvariantCulture, DateTimeStyles.None);

None of the above work. Sorry if my formatting is bad: first time posting a question here.

+3  A: 

Since you want to test that the data is XML compliant, you could use the XmlConvert.ToDateTime method:

DateTime dt = XmlConvert.ToDateTime(myDate);

This will throw a FormatException if the given string does not have the correct format.

Fredrik Mörk
+1  A: 

Just use XmlConvert.ToDateTime (note that XmlConvert.ToDateTime(string) is considered obsolete now and you should use XmlConvert.ToDateTime(string, XmlDateTimeSerializationMode).

However, if you insist on using DateTime.ParseExact (and there are good reasons to do so but then you should use DateTime.TryParseExact to avoid exception throwing in cases of fail) you can use the following format string:

string format = "yyyy-MM-ddTHH:mm:ss.fffzzz";

The parentheticals in the above paragraphs might be cumbersome to parse (I have a habit of doing that; sorry).

Jason