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

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


当前回答

原始示例:

/Date(1224043200000)/  

不反映WCF使用内置JSON序列化通过WCF REST发送日期时使用的格式。(至少在.NET 3.5 SP1上)

我发现这里的答案很有用,但需要对正则表达式进行轻微的编辑,因为似乎时区GMT偏移被附加到WCF JSON中返回的数字(自1970年以来)。

在WCF服务中,我有:

[OperationContract]
[WebInvoke(
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.WrappedRequest
    )]
ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );

ApptVisitLinkInfo的定义很简单:

public class ApptVisitLinkInfo {
    string Field1 { get; set; }
    DateTime Field2 { get; set; }
    ...
}

当“Field2”作为Json从服务返回时,值为:

/Date(1224043200000-0600)/

请注意作为值的一部分包含的时区偏移。

修改后的正则表达式:

/\/Date\((.*?)\)\//gi

它稍显急切,并抓住了家长之间的一切,而不仅仅是第一个数字。生成的时间sinze 1970,加上时区偏移都可以输入eval以获得日期对象。

替换产生的JavaScript行是:

replace(/\/Date\((.*?)\)\//gi, "new Date($1)");

其他回答

仅供参考,对于在服务器端使用Python的任何人:datetime.datetime().cctime()返回一个可通过“new Date()”进行本机解析的字符串。也就是说,如果您创建了一个新的datetime.datetime实例(例如使用datetime.ddatetime.now),该字符串可以包含在JSON字符串中,然后该字符串可以作为第一个参数传递给Date构造函数。我还没有发现任何异常,但我也没有对其进行过严格的测试。

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

想象一下:

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

我使用这个简单的函数从Microsoft JSON date获取日期

function getDateValue(dateVal) {
    return new Date(parseInt(dateVal.replace(/\D+/g, '')));
};

replace(/\D+/g,“”)将删除除数字以外的所有字符

parseInt将字符串转换为数字

用法

$scope.ReturnDate = getDateValue(result.JSONDateVariable)

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

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

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

在jQuery1.5中,只要您有json2.js来覆盖较旧的浏览器,就可以反序列化来自Ajax的所有日期,如下所示:

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

我包含了一个逻辑,假设您以UTC格式发送服务器上的所有日期(您应该这样做);消费者然后获得一个JavaScript Date对象,该对象具有适当的记号值来反映这一点。也就是说,在日期上调用getUTCHours()等将返回与服务器上相同的值,而调用getHours()将返回用户浏览器确定的本地时区值。

这没有考虑带有时区偏移的WCF格式,尽管添加起来相对容易。