Skip to content

Instantly share code, notes, and snippets.

@jcbozonier
Created January 28, 2012 05:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcbozonier/1692807 to your computer and use it in GitHub Desktop.
Save jcbozonier/1692807 to your computer and use it in GitHub Desktop.
Using a date reviver in JSON.parse
function dateReviver(key, value) {
if (typeof value === 'string') {
var 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;
};
JSON.parse(serialized_object, dateReviver);
@djdmbrwsk
Copy link

djdmbrwsk commented Jul 20, 2018

Note this doesn't revive dates that have an offset. Ex. 2018-07-20:08:00:00-04:00 🤓

Solution:

// ...
var 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(value);
}
// ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment