Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateTime.TryParseExact to verify XML Schema dateTime compliance

Tags:

c#

datetime

xsd

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.

like image 803
geardan Avatar asked Sep 15 '09 20:09

geardan


People also ask

How do you use DateTime TryParseExact?

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly.

How can I get date from XML file?

ToString("yyyy-MM-dd HH:mm:ss");

What is XS DateTime?

Lexical form The lexical form of xs:dateTime is a finite-length sequence of characters of the following form: yyyy - mm - dd T hh : mm : ss . ssssssssssss zzzzzz . The following abbreviations describe this form: yyyy. A four-digit numeral that represents the year.


1 Answers

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.

like image 100
Fredrik Mörk Avatar answered Sep 23 '22 02:09

Fredrik Mörk