Skip to content

Instantly share code, notes, and snippets.

@davehax
Created June 20, 2019 12:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davehax/2f32e7b09c3da3531601e6543fcff82e to your computer and use it in GitHub Desktop.
Save davehax/2f32e7b09c3da3531601e6543fcff82e to your computer and use it in GitHub Desktop.
// JSON.stringify({ date: new Date() }) --> '{"date":"2019-06-20T12:29:43.288Z"}'
// JSON.parse('{"date":"2019-06-20T12:29:43.288Z"}') --> { date: "2019-06-20T12:29:43.288Z" }
// hmm..
// let's use the following function to revive our Date objects!
function jsonDateReviver(key, value) {
// plug this regex into regex101.com to understand how it works
// matches 2019-06-20T12:29:43.288Z (with milliseconds) and 2019-06-20T12:29:43Z (without milliseconds)
var dateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,}|)Z$/;
if (typeof value === "string" && dateFormat.test(value)) {
return new Date(value);
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment