JavaScriptSerializer UTC DateTime issues

前端 未结 1 619
再見小時候
再見小時候 2020-11-28 12:49

Our client wanted to show the date and time values in the browser exactly as they are in the database, and we are storing them as UTC in the database.

At first we ha

相关标签:
1条回答
  • 2020-11-28 13:29

    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.

    0 讨论(0)
提交回复
热议问题