Skip to content

Instantly share code, notes, and snippets.

@mdeangelo272
Created January 24, 2013 00:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mdeangelo272/4616109 to your computer and use it in GitHub Desktop.
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.
// ******** 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