我将用jQuery首次尝试Ajax。我正在将数据放到页面上,但对于Date数据类型返回的JSON数据,我遇到了一些问题。基本上,我得到的字符串是这样的:

/Date(1224043200000)/

从一个对JSON完全陌生的人那里——我如何将其格式化为短日期格式?这应该在jQuery代码中的某个地方处理吗?我使用$.datepicker.formatDate()尝试了jQuery.UI.datepicker插件,但没有成功。

仅供参考:以下是我使用以下答案组合得出的解决方案:

function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}

这个解决方案从回调方法中获取了我的对象,并使用日期格式库在页面上正确显示了日期。


当前回答

我最终将“字符”添加到Panos的正则表达式中,以消除Microsoft序列化程序在将对象写入内联脚本时生成的字符:

所以,如果你的C#代码中有一个属性

protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}

在你的aspx中

<script type="text/javascript">
    var myObject = '<%= JsonObject %>';
</script>

你会得到类似的东西

var myObject = '{"StartDate":"\/Date(1255131630400)\/"}';

注意双引号。

为了将其转换为eval将正确反序列化的形式,我使用了:

myObject = myObject.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');

我使用原型,为了使用它,我添加了

String.prototype.evalJSONWithDates = function() {
    var jsonWithDates = this.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');
    return jsonWithDates.evalJSON(true);
}

其他回答

一篇迟来的帖子,但对那些搜索过这篇帖子的人来说。

想象一下:

    [Authorize(Roles = "Administrator")]
    [Authorize(Roles = "Director")]
    [Authorize(Roles = "Human Resources")]
    [HttpGet]
    public ActionResult GetUserData(string UserIdGuidKey)
    {
        if (UserIdGuidKey!= null)
        {
            var guidUserId = new Guid(UserIdGuidKey);
            var memuser = Membership.GetUser(guidUserId);
            var profileuser = Profile.GetUserProfile(memuser.UserName);
            var list = new {
                              UserName = memuser.UserName,
                              Email = memuser.Email ,
                              IsApproved = memuser.IsApproved.ToString() ,
                              IsLockedOut = memuser.IsLockedOut.ToString() ,
                              LastLockoutDate = memuser.LastLockoutDate.ToString() ,
                              CreationDate = memuser.CreationDate.ToString() ,
                              LastLoginDate = memuser.LastLoginDate.ToString() ,
                              LastActivityDate = memuser.LastActivityDate.ToString() ,
                              LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,
                              IsOnline = memuser.IsOnline.ToString() ,
                              FirstName = profileuser.FirstName ,
                              LastName = profileuser.LastName ,
                              NickName = profileuser.NickName ,
                              BirthDate = profileuser.BirthDate.ToString() ,
            };
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        return Redirect("Index");
    }

如您所见,我正在利用C#3.0的特性创建“Auto”泛型。它有点懒,但我喜欢它,而且很管用。请注意:Profile是我为web应用程序项目创建的自定义类。

在真棒线程中发布:

var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));
alert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));

只是在这里添加另一种方法,WCF采用的“滴答方法”如果您不非常小心,如这里和其他地方所述,则很容易出现时区问题。所以我现在使用的是.NET和JavaScript都适当支持的ISO 8601格式,其中包括时区偏移。详情如下:

在WCF/.NET中:

其中CreationDate是System.DateTime;ToString(“o”)使用.NET的往返格式说明符,该说明符生成符合ISO 8601的日期字符串

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

在JavaScript中

在检索JSON之后,我使用接受ISO 8601日期字符串的Date构造函数将日期修正为JavaSriptDate对象。。。

$.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());
    }
)

一旦有了JavaScript日期,就可以使用所有方便可靠的date方法,如toDateString、toLocaleString等。

我最终将“字符”添加到Panos的正则表达式中,以消除Microsoft序列化程序在将对象写入内联脚本时生成的字符:

所以,如果你的C#代码中有一个属性

protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}

在你的aspx中

<script type="text/javascript">
    var myObject = '<%= JsonObject %>';
</script>

你会得到类似的东西

var myObject = '{"StartDate":"\/Date(1255131630400)\/"}';

注意双引号。

为了将其转换为eval将正确反序列化的形式,我使用了:

myObject = myObject.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');

我使用原型,为了使用它,我添加了

String.prototype.evalJSONWithDates = function() {
    var jsonWithDates = this.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');
    return jsonWithDates.evalJSON(true);
}

已更新

我们有一个内部UI库,它必须同时处理Microsoft的ASP.NET内置JSON格式,如/Date(msecs)/(最初在这里询问),以及大多数JSON的日期格式(包括JSON.NET),如2014-06-22T00:00:00.0。此外,我们还需要应对旧IE无法处理除小数点后3位以外的任何内容。

我们首先检测我们使用的日期类型,将其解析为一个普通的JavaScriptDate对象,然后将其格式化。

1) 检测Microsoft日期格式

// Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'
function looksLikeMSDate(s) {
    return /^\/Date\(/.test(s);
}

2) 检测ISO日期格式

var isoDateRegex = /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(\.\d\d?\d?)?([\+-]\d\d:\d\d|Z)?$/;

function looksLikeIsoDate(s) {
    return isoDateRegex.test(s);
}

3) 分析MS日期格式:

function parseMSDate(s) {
    // Jump forward past the /Date(, parseInt handles the rest
    return new Date(parseInt(s.substr(6)));
}

4) 分析ISO日期格式。

我们至少有一种方法可以确保我们处理的是标准ISO日期或ISO日期修改为总是有三毫秒的位置(见上文),因此代码因环境而异。

4a)分析标准ISO日期格式,处理旧IE的问题:

function parseIsoDate(s) {
    var m = isoDateRegex.exec(s);

    // Is this UTC, offset, or undefined? Treat undefined as UTC.
    if (m.length == 7 ||                // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC
        (m.length > 7 && (
            !m[7] ||                    // Array came back length 9 with undefined for 7 and 8
            m[7].charAt(0) != '.' ||    // ms portion, no tz offset, or no ms portion, Z
            !m[8] ||                    // ms portion, no tz offset
            m[8] == 'Z'))) {            // ms portion and Z
        // JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.
        var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));
    } else {
        // local
        var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);
    }

    return d;
}

4b)使用固定的三毫秒小数位解析ISO格式-更容易:

function parseIsoDate(s) {
    return new Date(s);
}

5) 设置格式:

function hasTime(d) {
    return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());
}

function zeroFill(n) {
    if ((n + '').length == 1)
        return '0' + n;

    return n;
}

function formatDate(d) {
    if (hasTime(d)) {
        var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
        s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());
    } else {
        var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
    }

    return s;
}

6) 将其联系在一起:

function parseDate(s) {
    var d;
    if (looksLikeMSDate(s))
        d = parseMSDate(s);
    else if (looksLikeIsoDate(s))
        d = parseIsoDate(s);
    else
        return null;

    return formatDate(d);
}

下面的旧答案对于将这个日期格式绑定到jQuery自己的JSON解析中非常有用,这样您就可以得到date对象而不是字符串,或者如果您仍然被jQuery<1.5所困扰。

旧答案

如果将jQuery 1.4的Ajax函数与ASP.NET MVC结合使用,则可以使用以下命令将所有DateTime财产转换为Date对象:

// Once
jQuery.parseJSON = function(d) {return eval('(' + d + ')');};

$.ajax({
    ...
    dataFilter: function(d) {
        return d.replace(/"\\\/(Date\(-?\d+\))\\\/"/g, 'new $1');
    },
    ...
});

在jQuery1.5中,通过在Ajax调用中使用converters选项,可以避免全局重写parseJSON方法。

http://api.jquery.com/jQuery.ajax/

不幸的是,您必须切换到较旧的eval路由,以便将Dates全局解析到位,否则您需要在解析后逐个转换它们。