简体   繁体   中英

Using DateTime.TryParseExact to verify XML Schema dateTime compliance

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM