JavaScriptSerializer UTC DateTime issues

谁说胖子不能爱 提交于 2019-11-26 22:46:11

JavaScriptSerializer, and DataContractJsonSerializer are riddled with bugs. Use json.net instead. Even Microsoft has made this switch in ASP.Net MVC4 and other recent projects.

The /Date(286769410010)/ format is proprietary and made up by Microsoft. It has problems, and is not widely supported. You should use the 1979-02-02T02:10:10Z format everywhere. This is defined in ISO8601 and RF3339. It is both machine and human readable, lexically sortable, culture invariant, and unambiguous.

In JavaScript, if you can guarantee you will be running on newer browsers, then use:

date.toISOString()

Reference here.

If you want full cross-browser and older-browser support, use moment.js instead.

UPDATE

As an aside, if you really want to keep using JavaScriptSerializer, you could deserialize to a DateTimeOffset, which would preserve the correct time. You could then get the UTC DateTime from there, as follows:

// note, you were missing the milliseconds in your example, I added them here.
s = "\"1979-02-02T02:10:10.010Z\"";

dateActual = js.Deserialize<DateTimeOffset>(s).UtcDateTime;

Your test will now pass.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!