How Do I Serialize DateTime Objects in .NET in a Standards Compliant Way

Waylon Flinn picture Waylon Flinn · Apr 15, 2009 · Viewed 9.7k times · Source

My goal is use the .NET DateTime object (in C#) and have that be serialized to and parsed from a string (for use in XML) in a way that is standards compliant. The specific standard I have in mind is the ISO 8601 standard for representing dates and times.

I want an easy to use solution (preferably, one method call each way) that will convert to and from the concatenated version of the format. I would also like to preserve local time zone information.

Here's an example of the sort of string I'd like to get:

2009-04-15T10:55:03.0174-05:00

My target .NET version is 3.5.

I actually found a solution to this problem several years ago which involves a custom format and the DateTime.ToString(string) method. I was surprised that a simpler standards compliant solution didn't exist. Using a custom format string to serialize and parse in a standards compliant way smells a little to me.

Answer

Marc Gravell picture Marc Gravell · Apr 15, 2009

Fortunately, there is XmlConvert.ToString() and XmlConvert.ToDateTime() which handles this format:

string s = XmlConvert.ToString(DateTime.Now,
     XmlDateTimeSerializationMode.Local);
DateTime dt = XmlConvert.ToDateTime(s,
     XmlDateTimeSerializationMode.Local);

(pick your appropriate serialization-mode)