如何使用JSON.parse reviver参数来解析日期字符串 [英] How to use JSON.parse reviver parameter to parse date string
问题描述
我的JSON字符串包含一个返回这样一个值的日期字段:
My JSON string contains a date field that returns such a value:
"2009-04-04T22:55:16.0000000-04:00"
我特别感兴趣的是只解析日期室而不是时间。我尝试使用reviver功能,但有趣的是,reviver功能从未被调用! (在Firefox上尝试)
I am particularly interested in parsing only the date compartment not the time. I tried using a reviver function, but interestingly the reviver function is never invoked! (tried on 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);
....
});
}
};
中的JSON.parse loadArticle
从不调用 dateReviver
。
我投资了一整天,但没有运气!有人可以帮我吗
I invested a whole day but no luck! Could someone please help me?
推荐答案
-
正则表达式需要一个祖鲁时区(A'Z'在结束时),而采样日期时间字符串显示数字时区('-04:00')。以下正则表达式将同时接受:
The regular expression expects a "Zulu" timezone (A 'Z' character at the end), while the sample date-time string shows a numeric timezone ('-04:00'). The following regex will accept both:
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/
如果时区数字不为零,您可能需要在解析和/或转换为UTC后实际修改日期,以符合时区。
If the time zone digits are not zero, you might want to actually modify the date after parsing and/or converting to UTC, to respect the timezone.
我可以看到dateReviver()被击中。在浏览器中尝试以下操作:
I can see dateReviver() being hit. Try the following in a browser:
<!-- 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>
我在浏览器中收到以下内容,表示解析成功:
I am getting the following in the browser, indicating successful parsing:
Sat Apr 4 15:55:16 PDT 2009
这篇关于如何使用JSON.parse reviver参数来解析日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!