Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 515
Waylon Flinn Avatar asked Apr 15 '09 16:04

Waylon Flinn


People also ask

Can you serialize DateTime?

For serializing, you can use the DateTime(Offset). ToString method in your converter write logic. This method allows you to write DateTime and DateTimeOffset values using any of the standard date and time formats, and the custom date and time formats.

What is the most flexible way of serialization to store objects in an open standards based document?

The simplest thing to do is mark your objects with the Serializable attribute and then use a binary formatter to handle the serialization. The entire class graph shouldn't be a problem provided that any contained objects are also marked as Serializable.

Is DateTime value Type C#?

DateTime is a Value Type like int, double etc. so there is no way to assign a null value. When a type can be assigned null it is called nullable, that means the type has no value. All Reference Types are nullable by default, e.g. String, and all ValueTypes are not, e.g. Int32.

What does DateTime look like?

With the fractional part included, the format for these values is ' YYYY-MM-DD hh:mm:ss [. fraction ]' , the range for DATETIME values is '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999' , and the range for TIMESTAMP values is '1970-01-01 00:00:01.000000' to '2038-01-19 03:14:07.999999' .


2 Answers

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)

like image 116
Marc Gravell Avatar answered Oct 02 '22 20:10

Marc Gravell


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

like image 31
jlew Avatar answered Oct 02 '22 19:10

jlew