Simple way to deserialize DateTime strings

I recently came across a small problem when i was debugging an application. The app relied on a REST service and returned an XML result to me. An addition to the returned XML was that of a “start_date” element. Since we initially didn’t need to actually “do” anything with the “start_date” element, it was simply written out in pure text.

Later on, it suddenly became obvious that we needed to actually “do” something with it, so we needed to deserialize the element returned, and convert it into a DateTime object.

Now that’s not possible to do normally with the returned element..

1: <elements>
2: <otherelement />
3: …..
4: <start_date>2012-01-16 10:00:00</start_date>
5: …..
6: </elements>
 
The opposing definition for the “start_date” element – especially since the format was a bit off as well (US format).
 
1: [XmlElement(“start_date”)]
2: public stringStartDateString { get; set; }The solution is to have another property listed in
 
the deserialization class, which would take care of the conversion for us.
 
1: [XmlIgnore]
2: public DateTime StartDate
3: {
4: get { return DateTime.Parse(StartDateString, CultureInfo.InvariantCulture); }
5: }
First and foremost you decorate the “StartDate” property with [XmlIgnore] so that it doesn’t get deserialized – then it’s as simple as referencing the “StartDate” property as opposed to the “start_date” property when dealing with it.