Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

JavaScript - Best way to Detect Invalid Date Across Multiple Browsers

I'm trying to figure out if different browsers will return different messages/errors when a string is passed into a date function as per the below example where last[0] = "new visit":

var lastVisit = new Date(last[0]);

Open in new window


Chrome returns "Invalid Date" but not sure how robust this will be across all browsers if I'm using:

if(lastvisit != "Invalid Date")

Open in new window


I'm not sure if there is a better way to detect if I got a date format back or an invalid date? I can't do anything about the string being passed. It will happen the initial session a user hits the site.
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Please try...

IF ( isNAN(lastvisit) == False )
--- VALID DATE
Avatar of MJ

ASKER

I don't think that will work as the date object returns something like this Fri Dec 01 2017 22:01:37 GMT-0800 (Pacific Standard Time)
So what you need in return.
Avatar of MJ

ASKER

Just trying to find the best way to detect an invalid date.
Avatar of Dave Baldwin
JavaScript is very standardized across browsers.  There is no reason to think there will be differences.  Your biggest problem is that the date() function will try to return something that makes sense... even if it doesn't.  On this page https://www.w3schools.com/js/tryit.asp?filename=tryjs_date_new_string you can try all kinds of entries to see what happens.  When I entered '1923', it returned "Sun Dec 31 1922 16:00:00 GMT-0800 (Pacific Standard Time)".
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

Hi Julian,
Wouldn't that always be true since you are comparing the exact same thing or was there a typo???

if (dt.getTime() === dt.getTime())
It is one of the things about the invalid Date - getTime when compared to itself does not evaluate to true. Tested back to IE9 and all other browsers.