0

I need to verify is var is valid datetime object. This

alert( "dat::"+( typeof dat ))

returns "object". Which is the valid way ?

1
  • Hi, if you think my answer is the one that you were looking for, plz consider accepting it by clicking on the hallow checkmark. Commented Nov 24, 2014 at 17:53

2 Answers 2

2

Here is how I would do it:

if ( Object.prototype.toString.call(d) === "[object Date]" ) {
  // it is a date
}
else {
  // not a date
}
Sign up to request clarification or add additional context in comments.

3 Comments

Not sure it's possible for getTime to return NaN, unless it's the Date.prototype object or it's deliberately set to NaN. So why the second test?
Well you're right (I should have thought this through), maybe I can just remove the second test.
I think the first test is sufficient and as reliable as is possible.
1

Use instanceof:

dat instanceof Date

1 Comment

That will not work across frames. instanceof looks to see if the constructor's prototype is on the object's internal [[Prototype]] chain. That doesn't happen across frames since different Date constructors (and hence Date.prototype objects) are used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.