I have a class that I serialize/deserialize using XmlSerializer
. This class contains a DateTime
field.
When serialized, the DateTime
What I did, it was to use DateTime.SpecifyKind method, as following:
DateTime dateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified);
And this resolve my problem, I hope this help you.
Could you try something like this post suggests and make a new string property and XmlIgnore the existing one:
Put [XmlIgnore] on the Time property.
Then add a new property:
[XmlElement(DataType="string",ElementName="Time")]
public String TimeString
{
get { return this.timeField.ToString("yyyy-MM-dd"); }
set { this.timeField = DateTime.ParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture); }
}
I know this is old but hope this helps someone in the future.
Here is the XML I was deserializing:
<timePeriod>1982-03-31T00:00:00+11:00</t
After deserializing the XML I end up with the 30th not the 31st:
It appears the 3rd party who produce this XML (that I'm using) change the TimeZone to +11 during daylight saving and keep it as +10 when its not Daylight Saving (DST).
According to Jon Skeet UTC's shouldn't consider DST: https://stackoverflow.com/a/5495816/495455
The XML serializer always assumes that DateTime values being serialized represent local machine time, so it applies the machine local time zone offset as the offset portion of the encoded XML time. When we deserialize this onto another machine, the original offset is subtracted from the value being parsed, and the current machine's time-zone offset is added.
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");
DateTime easternTimeNow = TimeZoneInfo.ConvertTimeFromUtc(dataPoint.timePeriod, easternZone);
System.Diagnostics.Debug.WriteLine(easternTimeNow.ToString());
Hence the solution is fix the XML feed so it doesn't alternate UTC's with DST.
EDIT: why the data was screwed up
As it turns out its NOT the 3rd party vendor changing the UTC with the DST. The XML feed is created by Java Swing framework reading a SQL dB. Normally I would recommend keeping with the XML standard representation (xsd:dateTime) – IS0 8601, but in this case using string and ripping everything after the T works. Disclaimer, I am still trying to get the feed changed, recommend you do NOT do this in PROD. Use at your own risk!!
Instead of parsing as a DateTime
you can parse it as a DateTimeOffset
and use the DateTimeOffset.DateTime property to ignore the timezone. Like this:
[XmlIgnore()]
public DateTime Time { get; set; }
[XmlElement(ElementName = "Time")]
public string XmlTime
{
get { return XmlConvert.ToString(Time, XmlDateTimeSerializationMode.RoundtripKind); }
set { Time = DateTimeOffset.Parse(value).DateTime; }
}