First look at a chestnut:
JavaScriptSerializer serializer = new JavaScriptSerializer ();
DateTime now = DateTime.Parse ("2015-01-23 00:00:00");
Console.WriteLine (Serializer. Deserialize<datetime> (serializer. Serialize (now));
As shown in the figure above, the deserialization time is less than 8 hours ago, what is the cause? With Ilspy to JavaScriptSerializer decompile, get the source code as follows:
Javascriptserializer.serialize-> Javascriptserializer.serializedatetime:
private static void Serializedatetime (DateTime datetime, StringBuilder SB, Javascriptserializer.serializationformat Serializationformat)
{
if (Serializationformat = = JavascriptSerializer.SerializationFormat.JSON)
{
SB. Append ("\" \\/date (");
sb. Append (DateTime. ToUniversalTime (). ticks-javascriptserializer.datetimemintimeticks)/10000L);
sb. Append (") \\/\" ");
return;
}
sb. Append ("New Date (");
sb. Append (DateTime. ToUniversalTime (). ticks-javascriptserializer.datetimemintimeticks)/10000L);
sb. Append (")");
}
Javascriptserializer.deserialize-> javascriptobjectdeserializer.deserializestringintodatetime:
Copy content to Clipboard program code
Private Object Deserializestringintodatetime ()
{
match match = Regex.match ( This._s.tostring (), "^\" \\\\/date\\ (? <ticks>-?[ 0-9]+) (?: [A-za-z]| (?: \\+|-) [0-9]{4})? \) \\\\/\ "");
String value = Match. groups["Ticks"]. Value;
long num;
if (long. TryParse (value, out num))
{
this._s.movenext ( Match. Length);
datetime datetime = new DateTime (num * 10000L + Javascriptserializer.datetimemintimeticks, DATETIMEKIND.UTC);
return dateTime;
}
return this. Deserializestring ();
}
JavaScriptSerializer time to UTC time when deserialization, but not back to local time, local time and UTC time difference is 8 hours, which caused the above problem, therefore, After deserialization we need to call the ToLocalTime method to convert datetime to local time:
JavaScriptSerializer serializer = new JavaScriptSerializer ();
DateTime now = DateTime.Parse ("2015-01-23 00:00:00");
Console.WriteLine (Serializer. Deserialize<datetime> (serializer. Serialize (now)). ToLocalTime ());
Another workaround is to use the DataContractJsonSerializer class for serialization/deserialization, which does not have a problem above it.