How do I get .Net XML deserialization to preserve DateTimeKind?
I have an XML string with the following date: 2001-01-01T03:40:00Z
Note how it ends with Z,开发者_JAVA百科 to indicate UTC.
I deserialize like so:
using (StringReader stringReader = new StringReader(xmlString))
using (XmlReader xmlReader = XmlReader.Create(stringReader))
obj = (MyObject)sr.ReadObject(xmlReader);
But when I go to the corresponding DateTime fields in the resulting object, the Kind field is set to "Unspecified" rather than "Utc" which is what it should be. How do I work around this bug?
The Kind
field doesn't have a setter so the XmlSerializer won't be able to set it.
Many recommend always serializing the time as UTC and then calling ToLocalTime if you need it.
See this.
精彩评论