问题描述
我正在使用 jQuery 尝试 Ajax.我正在将我的数据放到我的页面上,但是我在处理为 Date 数据类型返回的 JSON 数据时遇到了一些问题.基本上,我得到了一个看起来像这样的字符串:
I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:
/Date(1224043200000)/
来自对 JSON 完全陌生的人 - 如何将其格式化为短日期格式?这应该在 jQuery 代码的某个地方处理吗?我已经使用 $.datepicker.formatDate()
尝试了 jQuery.UI.datepicker
插件,但没有成功.
From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker
plugin using $.datepicker.formatDate()
without any success.
仅供参考:这是我结合此处的答案提出的解决方案:
FYI: Here's the solution I came up with using a combination of the answers here:
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;
}
此解决方案从回调方法中获取我的对象,并使用日期格式库在页面上正确显示日期.
This solution got my object from the callback method and displayed the dates on the page properly using the date format library.
推荐答案
eval()
不是必需的.这会正常工作:
eval()
is not necessary. This will work fine:
var date = new Date(parseInt(jsonDate.substr(6)));
substr()
函数取出/Date(
部分,parseInt()
函数取出整数,忽略)/
最后.结果数字被传递到 Date
构造函数中.
The substr()
function takes out the /Date(
part, and the parseInt()
function gets the integer and ignores the )/
at the end. The resulting number is passed into the Date
constructor.
我故意省略了基数(parseInt
的第二个参数);请参阅我在下面的评论.
I have intentionally left out the radix (the 2nd argument to parseInt
); see my comment below.
另外,我完全同意 Rory 的评论:ISO-8601 日期优先于这种旧格式 - 因此这种格式通常不应用于新的开发.
Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.
对于 ISO-8601 格式的 JSON 日期,只需将字符串传递给 Date
构造函数:
For ISO-8601 formatted JSON dates, just pass the string into the Date
constructor:
var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
这篇关于如何格式化 Microsoft JSON 日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!