且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScriptSerializer 从日期中减去一天

更新时间:2023-11-23 21:02:52

它不会随意丢失一天,而是转换为 UTC 日期(或者我应该说使用 UTC 日期格式的日期),所以当它被反序列化时,你不再在您的个人时区内.它基本上是在执行:

It's not losing a day arbitrarily, it's converting to a UTC date (or I should say using the date in a UTC date format) so when it's unserialized it you're no longer within your personal time zone. It's basically performing:

DateTime whateverDate = /* incoming date */;
long ticks = whateverDate.ToUniversalTime() // make UTC
  .Subtract(new DateTime(1970, 1, 1))       // subtract UNIX Epoch
  .TotalMilliseconds();                     // get milliseconds since then
// push in to the "/Date(ticks)/" format
String value = String.Format(@"/Date({0})/", ticks);

但是,请尝试以下操作:

However, try the following:

// or you rely on it serializing, then bring it back to your own local time
// (apply the time zone).
afterDeserialize = afterDeserialize.ToLocalTime();

您现在会将 UTC 时间恢复为您的本地时间(应用时区).

You'll now have the UTC time back to your local time (with time zone applied).

要通过测试:

DateTime startDate              = new DateTime(2012,1,20);
JavaScriptSerializer serializer = new JavaScriptSerializer();
String serializeDate            = serializer.Serialize(startDate);
DateTime afterDeserialize       = serializer.Deserialize<DateTime>(serializeDate)
                                  .ToLocalTime(); // Note: this is added

Assert.Equals(startDate, afterDeserialize); // pass!