If I save a .NET DateTime using System.Web.Script.Serialization.JavaScriptSerializer the deserialized version is an hour different than the original version. Any ideas why?
EDIT: My workstation’s time zone is UTC.
A NUnit test is below; note that the assertion works only after adding an hour.
[Test]
public void JsonSerializationOfDateTimesDoesntWork()
{
var originalDateTime = new DateTime(2011, 6, 20, 6, 5, 4, 3);
const string fileName = "C:\\temp\\testDateTime.json";
using (var writer = new StreamWriter(fileName, false))
{
writer.Write(new JavaScriptSerializer().Serialize(originalDateTime));
}
DateTime newDateTime;
using (var reader = new StreamReader(fileName, false))
{
var readToEnd = reader.ReadToEnd();
newDateTime = new JavaScriptSerializer().Deserialize<DateTime>(readToEnd);
}
Assert.AreEqual(originalDateTime, newDateTime.AddHours(1)); // !!
}
The serializer apparently converts it to an instant in time, in the form of milliseconds since the unix epoch. In other words, it’s effectively calling
ToUniversalTime()first.At that point, any information about the original “kind” of
DateTimeis lost.On deserialization, the result is always a
DateTimeof kind UTC.If you start with a
DateTimewith a kind of UTC, you’ll round-trip. If you need to remember the kind as well, you’ll need to keep that data separately. Just remember that local times can be inherently ambiguous.Output:
Of course, this just highlights the problems with
DateTimebeing conceptually broken to start with…EDIT: Also, as noted in comments, I very much doubt that your workstation’s time zone is really UTC, by the way. I suspect it’s the UK time zone, which is UTC in winter, but UTC+1 in summer – and the date you’ve given is in summer.