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

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


当前回答

在以下代码中。我有

1.从日期字符串中检索到时间戳。

2.并将其解析为Int

3.最终使用它创建了日期。

var dateString=“/Date(1224043200000)/”;var seconds=parseInt(dateString.replace(/\/Date\(([0-9]+)[^+]\//i,“$1”));var date=新日期(秒);console.log(日期);

其他回答

您还可以使用JavaScript库moment.js,当您计划处理不同的本地化格式并使用日期值执行其他操作时,它会很方便:

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

    function (result) {
        $("#AuthMerchId").text(result.AuthorizationMerchantId);
        $("#SttlMerchId").text(result.SettlementMerchantId);
        $("#CreateDate").text(moment(result.AppendDts).format("L"));
        $("#ExpireDate").text(moment(result.ExpiresDts).format("L"));
        $("#LastUpdate").text(moment(result.LastUpdateDts).format("L"));
        $("#LastUpdatedBy").text(result.LastUpdateNt);
        $("#ProcessIn").text(result.ProcessIn);
    }
    );
    return false;
}

设置本地化就像向项目中添加配置文件(您可以在momentjs.com上获得)并配置语言一样简单:

moment.lang('de');

原始示例:

/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)");

JSON可能会返回某种类型的对象(嗯,是其字符串表示)。

"{ myDate : Date(1224043200000) }"

使用jQuery,您可以通过以下方式访问数据对象:

$.get(
    "myJSONFile.php",
    function (data) {
        // data.myDate will be a date object.

        // to show in a short date format (eg: dd/mm/yyyy)
        alert (
            data.myDate.getDate() + "/"
            + (data.myDate.getMonth() + 1) + "/"
            + data.myDate.getFullYear()
        ); // alerts: "15/10/2008"
    }
);

另一个正则表达式示例可以尝试使用:

var mydate = json.date
var date = new Date(parseInt(mydate.replace(/\/Date\((-?\d+)\)\//, '$1');
mydate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();

date.getMonth()返回一个0-11的整数,所以我们必须加1才能得到正确的月份数

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