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

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


当前回答

单击此处查看演示

JavaScript/jQuery

var = MyDate_String_Value = "/Date(1224043200000)/"
var value = new Date
            (
                 parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
            );
var dat = value.getMonth() +
                         1 +
                       "/" +
           value.getDate() +
                       "/" +
       value.getFullYear();

结果-“2008年10月15日”

其他回答

在以下代码中。我有

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

2.并将其解析为Int

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

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

另外,KendoUI支持转换Microsoft JSON日期。因此,如果您的项目引用了“KendoUI”,您可以简单地使用

var newDate = kendo.parseDate(jsonDate);

我最终将“字符”添加到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);
}

我可以建议的最简单的方法是在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] 

如果.NET返回。。。

return DateTime.Now.ToString("u"); //"2013-09-17 15:18:53Z"

然后在JavaScript中。。。

var x = new Date("2013-09-17 15:18:53Z");