How do I format a Microsoft JSON date?

后端 未结 30 3085
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:48

I\'m taking my first crack at Ajax with jQuery. I\'m getting my data onto my page, but I\'m having some trouble with the JSON data that is returned for Date data types. Basi

30条回答
  •  终归单人心
    2020-11-21 05:12

    Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:

    In WCF/.NET:

    Where CreationDate is a System.DateTime; ToString("o") is using .NET's Round-trip format specifier that generates an ISO 8601-compliant date string

    new MyInfo {
        CreationDate = r.CreationDate.ToString("o"),
    };
    

    In JavaScript

    Just after retrieving the JSON I go fixup the dates to be JavaSript Date objects using the Date constructor which accepts an ISO 8601 date string...

    $.getJSON(
        "MyRestService.svc/myinfo",
        function (data) {
            $.each(data.myinfos, function (r) {
                this.CreatedOn = new Date(this.CreationDate);
            });
            // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
           alert(data.myinfos[0].CreationDate.toLocaleString());
        }
    )
    

    Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.

提交回复
热议问题