Serializing DateTime to XML

The XmlConvert class has been obsolete since .NET 2.0. I found this out when I needed to manually serialize and deserialize DateTime values to XML and all the examples used the old class. After some researching I found out that the following call will return the date time alue in the same format as the XmlSerializer uses:

Returns “2008-11-17T12:28:09.9862678+02:00”

The value is easily converted back using the DateTime.Parse() function.

If you happen to need the functions of the XmlConvert class, you can achive the same results by combining the XmlSerializer with the TextWriter/TextReader classes. The following deserializes a XML value back to the correct type.

XmlSerializer dateSerializer = new XmlSerializer(type);
StringReader reader = new StringReader(stringValue);
return dateSerializer.Deserialize(reader);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s