Skip to content

Instantly share code, notes, and snippets.

@robnyman
Created February 13, 2012 23:55
Show Gist options
  • Save robnyman/1821580 to your computer and use it in GitHub Desktop.
Save robnyman/1821580 to your computer and use it in GitHub Desktop.
Serializing dates with JSON
var date = new Date();
console.log(date);
var dateAsString = JSON.stringify(date);
console.log(dateAsString);
var dateAsObj = new Date(JSON.parse(dateAsString));
console.log(dateAsObj);
@peterjaric
Copy link

What I am afraid of is putting the date parsing code deep down in the code that uses the structure. Since the stringification of the Date object is a side effect of me using caching (lscache) elsewhere, that code should need to care about it. Likewise, the caching code should not need to know about the structure and contents of the data (that there is a date here and something else there).

I think I need to rethink my implementation or write a wrapper that can automatically recognize Dates, etc and parse them (by prefixing values in the JSON with the data type, perhaps).

Thanks for your help, it's very much appreciated!

@robnyman
Copy link
Author

I understand. Well, you need to assess what you need to do and what works best for you.
Good luck!

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