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

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


当前回答

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

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

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

parseInt将字符串转换为数字

用法

$scope.ReturnDate = getDateValue(result.JSONDateVariable)

其他回答

eval()不是必需的。这将很好:

var date = new Date(parseInt(jsonDate.substr(6)));

substr()函数取出/Date(部分),parseInt()函数获取整数并忽略结尾处的)/。生成的数字被传递到Date构造函数中。


我故意省略了基数(parseInt的第二个参数);请看我下面的评论。

此外,我完全同意Rory的评论:ISO-8601日期比这种旧格式更可取,因此这种格式通常不应用于新的开发。

对于ISO-8601格式的JSON日期,只需将字符串传递到Date构造函数:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

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

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才能得到正确的月份数

这也可能对你有所帮助。

 function ToJavaScriptDate(value) { //To Parse Date from the Returned Parsed Date
        var pattern = /Date\(([^)]+)\)/;
        var results = pattern.exec(value);
        var dt = new Date(parseFloat(results[1]));
        return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    }

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

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