Created
January 24, 2013 00:12
-
-
Save mdeangelo272/4616109 to your computer and use it in GitHub Desktop.
This simple gist will parse JSON data and convert datetime string to proper date objects. It can be extended to include other date string formats.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ******** Date Parsing ******** | |
var jsonDates = { | |
dtrx2: /\d{4}-\d{2}-\d{2}/, | |
parse: function(obj){ | |
var parsedObj = JSON.parse(obj); | |
return this.parseDates(parsedObj); | |
}, | |
parseDates: function(obj){ | |
// iterate properties | |
for(pName in obj){ | |
// make sure the property is 'truthy' | |
if (obj[pName]){ | |
var value = obj[pName]; | |
// determine if the property is an array | |
if (Array.isArray(value)){ | |
for(var ii = 0; ii < value.length; ii++){ | |
this.parseDates(value[ii]); | |
} | |
} | |
// determine if the property is an object | |
else if (typeof(value) == "object"){ | |
this.parseDates(value); | |
} | |
// determine if the property is a string containing a date | |
else if (typeof(value) == "string" && this.dtrx2.test(value)){ | |
// parse and replace | |
obj[pName] = new Date(obj[pName]); | |
} | |
} | |
} | |
return obj; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment