Skip to content

Instantly share code, notes, and snippets.

@hassanuos
Forked from mdeangelo272/JsonDates.js
Created December 30, 2021 12:02
Show Gist options
  • Save hassanuos/145b7b9d4f6d4ffe31eb27c340cc6f4a to your computer and use it in GitHub Desktop.
Save hassanuos/145b7b9d4f6d4ffe31eb27c340cc6f4a 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