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

Ah, I see. My situation is that I am trying to put an object with a Date embedded far down into localStorage. E.g.:

var o = { name: "Peter", data: { date: new Date(), score: 123 } }

If I want to store that object in LS I guess I need to create a wrapper library that knows about special kinds of objects?

Maybe the already exisiting wrapper libraries (i.e. those that @pamelafox mentioned at Jfokus) do this already. The caching wrapper lscache doesn't seem to do it (that's where I ran into it).

@robnyman
Copy link
Author

Well, you could stringify the date on its own as part of an object, and then parse into an object again when you access it:

var date = new Date();
console.log(date);
var dateAsString = JSON.stringify(date);

var testObj = {
name : "Peter",
date : dateAsString
};

var objAsString = JSON.stringify(testObj);
var objAsObj = JSON.parse(objAsString);
console.log(objAsObj);
console.log(JSON.parse(objAsObj.date));

@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