Date object creation fails in JavaScript

I'm getting very strange error in JavaScript.

var stamp = 1349102;
var obj = {a: stamp, b: new Date(stamp), c: new Date(1349102)};

When I look into obj - b says invalid Date but c is valid Date object.

Please help me. I really don't know how to solve this issue.

Upvotes: 1

Views: 92

Answers (1)

Tom
Tom

Reputation: 26819

If stamp is provided by a user, it can be considered as string. In that case your code would be interpreted by a browser as the following code (which does not work):

var stamp = "1349102";
var obj = {a: stamp, b: new Date(stamp), c: new Date(1349102)};

Convert stamp to Number and it will be fine

var stamp = "1349102";
var obj = {a: stamp, b: new Date(Number(stamp)), c: new Date(1349102)};

See the console output: first is without Number conversion, second is with Number conversion.

JSON Console Output

Upvotes: 1

Related Questions