How do I format a Microsoft JSON date?

后端 未结 30 3190
伪装坚强ぢ
伪装坚强ぢ 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:09

    I get the date like this:

    "/Date(1276290000000+0300)/"
    

    In some examples the date is in slightly different formats:

    "/Date(12762900000000300)/"
    "Date(1276290000000-0300)"
    

    etc.

    So I came up with the following RegExp:

    /\/+Date\(([\d+]+)\)\/+/
    

    and the final code is:

    var myDate = new Date(parseInt(jsonWcfDate.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));
    

    Hope it helps.

    Update: I found this link from Microsoft: How do I Serialize Dates with JSON?

    This seems like the one we are all looking for.

    0 讨论(0)
  • 2020-11-21 05:10

    You can use this to get a date from JSON:

    var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
    

    And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

    0 讨论(0)
  • 2020-11-21 05:11

    eval() is not necessary. This will work fine:

    var date = new Date(parseInt(jsonDate.substr(6)));
    

    The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor.


    I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below.

    Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development. See the excellent Json.NET library for a great alternative that serializes dates using the ISO-8601 format.

    For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

    var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
    
    0 讨论(0)
  • 2020-11-21 05:12

    In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:

    (function () {
        var DATE_START = "/Date(";
        var DATE_START_LENGTH = DATE_START.length;
    
        function isDateString(x) {
            return typeof x === "string" && x.startsWith(DATE_START);
        }
    
        function deserializeDateString(dateString) {
            var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
            var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
            return utcDate;
        }
    
        function convertJSONDates(key, value) {
          if (isDateString(value)) {
            return deserializeDateString(value);
          }
          return value;
        }
    
        window.jQuery.ajaxSetup({
          converters: {
            "text json": function(data) {
              return window.JSON.parse(data, convertJSONDates);
            }
          }
        });
    }());
    

    I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date object that has the proper ticks value to reflect this. That is, calling getUTCHours(), etc. on the date will return the same value as it did on the server, and calling getHours() will return the value in the user's local timezone as determined by their browser.

    This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 05:15

    Check up the date ISO standard; kind of like this:

    yyyy.MM.ddThh:mm
    

    It becomes 2008.11.20T22:18.

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