Slicky
Slicky

Reputation: 97

String was not recognized as a valid DateTime (valid UTC format)

I'm trying to deserialize an XML object with the following node:

<startTime>2012-03-19T11:31:03.000Z</startTime>
<endTime>2012-03-19T11:31:03.000Z</endTime>

Those are the properties on the class which I use to deserialize the XML into:

[System.Xml.Serialization.XmlElementAttribute(DataType = "date", ElementName = "startTime")]
public DateTime StartTime { get; set; }

[System.Xml.Serialization.XmlElementAttribute(DataType = "date", ElementName = "endTime")]
public DateTime EndTime { get; set; }

Finally, this is the code I use to deserialize the XML:

Stream resultStream = await response.Content.ReadAsStreamAsync();
var serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(resultStream) as T;

However, the code will throw an Exception, telling me that the string was not recognized as a valid DateTime object - with a base exception saying that the XML file has errors at (1,1926) which points directly to the two timestamps.

All I can seem to find regarding this error message is caused by incorrect usage of formats (i.e. wrong special characters used in the date string). However, in my case, the format seems to comply 100% with the MSDN description.

Can anybody help me to point out the mistake?

Upvotes: 4

Views: 5493

Answers (2)

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You are trying to Deserialize a DateTime using the Time format which can't work. But you don't get an error message at compilation because the DataType is a string.

You should try:

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "startTime")]
public DateTime StartTime { get; set; }

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "endTime")]
public DateTime EndTime { get; set; }

Upvotes: 1

Hugh
Hugh

Reputation: 454

Try using the "dateTime" DataType in your attributes - (watch the case: starting with a small d):

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "startTime")]
public DateTime StartTime { get; set; }

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "endTime")]
public DateTime EndTime { get; set; }

Upvotes: 4

Related Questions