Store `new Date ()` In JSON Object
I have the following field validator object: { type:'date', 'min':new Date() } I was hoping that I could store new Date() as an expression in JSON and it would be executed when it
Solution 1:
save the timestamp:
{ type:'date', 'min':(new Date()).getTime() }
then you read it back:
var result = JSON.parse('{ "type":"date", "min":1234567 }');
result.date = new Date(result.min);
Note: the server you use to serialize it and the server you use to deserialize it has to run in the same timezone
Solution 2:
You can't store the complete Date object in a JSON string. But you can try to store a text representing him :
As a string :
{ type:'date', 'min':(new Date()).toString() }
As a timestamp :
{ type:'date', 'min':(new Date()).getTime() }
As an ISO string :
{ type:'date', 'min':(new Date()).toJSON() }
Solution 3:
JSON does not support the Date datatype (it only supports string number, object, array, true, false, and null). You need to convert it to a string instead.
For example, ISO time:
var json = JSON.stringify( { type:'date', 'min':new Date().toISOString() } );
document.body.appendChild(document.createTextNode(json));
Solution 4:
The date object, actually has a toJSON
method, which you might find useful. However I suggest using getTime
as it returns a timestamp, which is usually more flexible.
Post a Comment for "Store `new Date ()` In JSON Object"