Using XmlConvert for DateTime Strings

James Newton-King, developer of the JSON.NET project, notes that it gets harder to be a .NET developer with every release. He reposted a chart from Brad Abrams showing the growth of the number of types in the Microsoft .NET framework.

More Types in Microsoft.NET Every Year

We’ve run into this problem all the time developing infovark. Often, it’s not the sheer size of the framework that proves challenging, but finding just the right method to do just the right thing.

A case in point was a recent problem I had in converting a DateTime object into a string properly formatted for XML. Normally you’d do something like this:

string theDateString = myDateTime.ToString();

This gives you a string in the .NET format, but that’s not the correct format for XML Schema (XSD). No problem, you think, I’ll just pass a format argument to the ToString method. So you look up the available string formatting options on MSDN. There’s lots of choices here, from the “based on ISO 8601″ format to the “RFC1123Pattern” to the “UniversalSortableDateTimePattern”. But it turns out that none of these formats work for XML if you want it to validate against your XML Schema. What gives? Do you have to provide a custom formatting string to get the date pattern you want?

It turns out that you’re looking in the wrong place entirely. These aren’t the string formats you’re looking for. Move along.

What you want is in the System.Xml namespace. You want the XmlConvert class. The XmlConvert class lets you convert from native .NET types to valid XML and back. The code looks like this:

string theDateString = XmlConvert.ToString(myDateTime);

It’s not only the size of the .NET framework that’s daunting. It’s the fact that functionality can be duplicated — or worse — made just slightly different across all of those classes. It puts developers in an awkward situation. Do they spend time researching to figure out exactly which method of which class in which namespace ought to be used in a given situation? Or do they roll their own (possibly buggy) implementation? It’s a tough call.

Personally, I’d like to see more guidance from Microsoft — perhaps through their code analysis tools — as to the preferred way of doing common tasks.

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: