admin管理员组文章数量:1317131
I have a problem with parsing dates in my jQuery-ajax response in json format.
My client side code:
$.ajax({
url: '/index',
dataType: 'json',
success: function (data) {
console.log(data.date);
}
});
Server is sending json:
{
"name": "john",
"date": "2013-07-01T00:00:00",
}
After running my client side code I receive in console a string content:
2013-07-01T00:00:00
which is not a date type. I thought that it would be done by the parser. What do I have to do to have my dates parsed automatically during json parsing?
Chris
I have a problem with parsing dates in my jQuery-ajax response in json format.
My client side code:
$.ajax({
url: '/index',
dataType: 'json',
success: function (data) {
console.log(data.date);
}
});
Server is sending json:
{
"name": "john",
"date": "2013-07-01T00:00:00",
}
After running my client side code I receive in console a string content:
2013-07-01T00:00:00
which is not a date type. I thought that it would be done by the parser. What do I have to do to have my dates parsed automatically during json parsing?
Chris
Share Improve this question edited Apr 24, 2013 at 4:31 cryss asked Apr 23, 2013 at 18:25 crysscryss 4,5091 gold badge32 silver badges36 bronze badges2 Answers
Reset to default 6Ok, I have found a nice solution from http://erraticdev.blogspot./2010/12/converting-dates-in-json-strings-using.html:
/*!
* jQuery.parseJSON() extension (supports ISO & Asp date conversion)
*
* Version 1.0 (13 Jan 2011)
*
* Copyright (c) 2011 Robert Koritnik
* Licensed under the terms of the MIT license
* http://www.opensource/licenses/mit-license.php
*/
(function ($) {
// JSON RegExp
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z?/i;
var dateNet = /\/Date\((\d+)(?:-\d+)?\)\//i;
// replacer RegExp
var replaceISO = /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?Z?"/i;
var replaceNet = /"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/i;
// determine JSON native support
var nativeJSON = (window.JSON && window.JSON.parse) ? true : false;
var extendedJSON = nativeJSON && window.JSON.parse('{"x":9}', function(k,v){return "Y";}) === "Y";
var jsonDateConverter = function(key, value) {
if (typeof(value) === "string") {
if (dateISO.test(value)) {
if (value == '0001-01-01T00:00:00') {
return null;
}
return new Date(value);
}
if (dateNet.test(value))
{
return new Date(parseInt(dateNet.exec(value)[1], 10));
}
}
return value;
};
$.extend({
parseJSON: function(data, convertDates) {
/// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary>
/// <param name="data" type="String">The JSON string to parse.</param>
/// <param name="convertDates" optional="true" type="Boolean">Set to true when you want ISO/Asp dates to be auto-converted to dates.</param>
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim(data);
// Make sure the ining data is actual JSON
// Logic borrowed from http://json/json2.js
if (rvalidchars.test(data
.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, "")))
{
// Try to use the native JSON parser
if (extendedJSON || (nativeJSON && convertDates !== true))
{
return window.JSON.parse(data, convertDates === true ? jsonDateConverter : undefined);
}
else {
data = convertDates === true ?
data.replace(replaceISO, "new Date(parseInt('$1',10),parseInt('$2',10)-1,parseInt('$3',10),parseInt('$4',10),parseInt('$5',10),parseInt('$6',10),(function(s){return parseInt(s,10)||0;})('$7'))")
.replace(replaceNet, "new Date($1)"):
data;
return (new Function("return " + data))();
}
} else
{
$.error("Invalid JSON: " + data);
}
}
});
})(jQuery);
usage:
$.ajax({
url: '/index',
// dataType: 'json', <- remove it
converters: {
"text json": function (data) {
return $.parseJSON(data, true);
}
},
success: function (data) {
console.log(data.date);
}
});
just like this
var myDate = new Date("2013-07-01T00:00:00")
JavaScript supports ISO 8601 parsing out of the box
本文标签: javascriptParsing iso dates in jQuery ajax json responseStack Overflow
版权声明:本文标题:javascript - Parsing iso dates in jQuery ajax json response - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741998369a2410507.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论