Using DateTime.TryParseExact to Validate DateTime XML Schema

I am trying to verify that the C # string is in the DateTime XML Schema format. Looking at MSDN, it seems that the standard format strings "o", "s" or "u" can describe valid dates, but I cannot 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: for the first time I am asking a question here.

+7
c # datetime xsd
source share
2 answers

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

 DateTime dt = XmlConvert.ToDateTime(myDate); 

This will FormatException if the specified string does not have the correct format.

+14
source share

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

However, if you insist on using DateTime.ParseExact (and there are good reasons for this, but then you should use DateTime.TryParseExact to avoid throwing exceptions in case of failure), you can use the following format line:

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

The brackets in the paragraphs above can be cumbersome to parse (I have a habit of doing this, sorry).

+9
source share

All Articles