我的JSON字符串包含一个返回此值的日期字段:
"2009-04-04T22:55:16.0000000-04:00"
我对仅解析日期分隔而不是时间解析特别感兴趣。我尝试使用reviver函数,但有趣的是,从未调用过reviver函数!(在Firefox上试用)
这是我要完成的代码:
var Site = { ..... dateReviver: function(key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }, loadArticle: function(id) { .... proxy.getArticle(id, function(response) { var data = JSON.parse(response.result, Site.dateReviver); .... }); } };
loadArticle永不调用JSON.parse dateReviver。
loadArticle
dateReviver
我花了一整天,但没有运气!有人可以帮我吗?
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/
如果时区数字不为零,则您可能要在解析和/或转换为UTC之后实际修改日期,以遵守时区。
<!-- saved from url=(0014)about:internet --> <html> <head> <script src="http://www.json.org/json2.js"></script> <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js"></script> <script> $(function () { // a mock proxy to return some json to play with var proxy = { getArticle: function(id, foo) { foo({ result: '["2009-04-04T22:55:16.0000000-04:00"]' }); } }; // the origial Site object, with the fixed regex var Site = { dateReviver: function(key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }, loadArticle: function(id) { proxy.getArticle(id, function(response) { var data = JSON.parse(response.result, Site.dateReviver); // put the parsed JSON date on the page $("#output").html(data[0].toString()); }); } }; // try out our Site object Site.loadArticle(); }); </script> </head> <body> <div id="output"></div> </body> </html>
我在浏览器中得到以下指示成功解析的信息:
Sat Apr 4 15:55:16 PDT 2009