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.


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)


dateobj.ToString(“s”)将为您提供符合ISO 8601的字符串表示形式,然后可以使用DateTime.Parse()进行反序列化


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)

链接地址: http://www.djcxy.com/p/8128.html

上一篇: DateTime和xsd:date的往返XML序列化?

下一篇: 如何以符合标准的方式在.NET中序列化DateTime对象