How to serialize DateTime objects in .NET according to standards

My goal is to use a .NET DateTime object (in C #) and serialize it and parse from a string (for use in XML) in a way that complies with standards. The specific standard that I have in mind is the ISO 8601 standard for representing dates and times.

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

Here is an example of the line I would like to get:

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

My target version of .NET is 3.5.

I really found a solution to this problem a few years ago, which includes a custom format and the DateTime.ToString (string) method. I was surprised that a simpler, standards-compliant solution does not exist. Using custom format strings for serialization and parsing according to standards smells a bit to me.

+7
datetime
source share
4 answers

Fortunately, there are XmlConvert.ToString() and XmlConvert.ToDateTime() that handle this format:

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

(select the appropriate serialization mode)

+15
source share

dateobj.ToString ("s") will give you a standard view that complies with the ISO 8601 standard, which can then be deserialized using DateTime.Parse ()

+4
source share

It seems that in recent years, .NET has improved a bit in this regard. The System.Xml.XmlConvert object is apparently designed to address the whole class of needs that appear in this context. The following functions appear to be specifically designed to convert transformations of DateTime objects in a flexible and standard way.

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

The following enumeration member seems especially useful if you want to keep the original time zone information:

 System.Xml.XmlDateTimeSerializationMode.RoundtripKind 

Here are the documentation links for functions on MSDN:

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

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

+3
source share

Try the following:

 System.Xml.XmlConvert.ToString(TimeStamp, System.Xml.XmlDateTimeSerializationMode.Utc)) 
+1
source share

All Articles