stackoverfloweth
stackoverfloweth

Reputation: 6917

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's parsed

Upvotes: 4

Views: 15400

Answers (4)

Gavriel
Gavriel

Reputation: 19237

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

Upvotes: 3

Vinks
Vinks

Reputation: 156

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() }

Upvotes: 3

Quentin
Quentin

Reputation: 943999

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));

Upvotes: 1

GMchris
GMchris

Reputation: 5648

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.

Upvotes: 0

Related Questions