Waylon Flinn
Waylon Flinn

Reputation: 20257

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

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.

Upvotes: 9

Views: 10792

Answers (4)

jlew
jlew

Reputation: 10591

dateobj.ToString("s") will get you an ISO 8601-compliant string representation, which can then be deserialized with DateTime.Parse()

Upvotes: 5

dthrasher
dthrasher

Reputation: 41812

Try this:

System.Xml.XmlConvert.ToString(TimeStamp, System.Xml.XmlDateTimeSerializationMode.Utc))

Upvotes: 1

Waylon Flinn
Waylon Flinn

Reputation: 20257

It looks like .NET has improved a little in this regard over the past few years. The System.Xml.XmlConvert object seems to be designed to address a whole class of needs that appear in this context. The following functions appear to be designed specifically to address conversion of DateTime objects in a flexible and standards compliant way.

XmlConvert.ToDateTime(string, System.Xml.XmlDateTimeSerializationMode)


XmlConvert.ToString(DateTime, System.Xml.XmlDateTimeSerializationMode)

The following enumeration member seems especially useful in the case that you want to preserve the original time zone information:

System.Xml.XmlDateTimeSerializationMode.RoundtripKind

Here are links to documentation for the functions on MSDN:

XmlConvert.ToDateTime(string, System.Xml.XmlDateTimeSerializationMode)

XmlConvert.ToString(DateTime, System.Xml.XmlDateTimeSerializationMode)

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1063338

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)

Upvotes: 16

Related Questions