我将用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;
}

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


当前回答

只是在这里添加另一种方法,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等。

其他回答

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

想象一下:

    [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应用程序项目创建的自定义类。

我可以建议的最简单的方法是在JS上使用正则表达式:

//Only use [0] if you are sure that the string matches the pattern
//Otherwise, verify if 'match' returns something
"/Date(1512488018202)/".match(/\d+/)[0] 

使用jQuery UI日期选择器-只有在已经包含jQuery UI的情况下才有意义:

$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6)))); 

输出:

2008年10月15日

只是在这里添加另一种方法,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等。

不要重复自己的操作-使用$.parseJSON()自动进行日期转换

帖子的答案提供了手动日期转换为JavaScript日期。我对jQuery的$.parseJSON()进行了一点点扩展,因此它能够在您指示时自动解析日期。它处理ASP.NET格式的日期(/Date(12348721342)/)以及ISO格式的日期,这些日期由浏览器中的原生JSON函数(以及json2.js等库)支持。

无论如何如果你不想一次又一次重复你的日期转换代码,我建议你阅读这篇博客文章,并获得代码,这将使你的生活更轻松。