How do I format a Microsoft JSON date?

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

    For those using Newtonsoft Json.NET, read up on how to do it via Native JSON in IE8, Firefox 3.5 plus Json.NET.

    Also the documentation on changing the format of dates written by Json.NET is useful: Serializing Dates with Json.NET

    For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the IsoDateTimeConverter(). Note that since Json.NET 4.5 the default date format is ISO so the code below isn't needed.

    string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());
    

    The JSON will come through as

    "fieldName": "2009-04-12T20:44:55"
    

    Finally, some JavaScript to convert the ISO date to a JavaScript date:

    function isoDateReviver(value) {
      if (typeof value === 'string') {
        var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);
          if (a) {
            var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
            return new Date(utcMilliseconds);
          }
      }
      return value;
    }
    

    I used it like this

    $("").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo("#" + divName);
    

提交回复
热议问题