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.
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.
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.
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.
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' .
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")
will get you an ISO 8601-compliant string representation, which can then be deserialized with DateTime.Parse()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With