MJ
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":
Chrome returns "Invalid Date" but not sure how robust this will be across all browsers if I'm using:
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.
var lastVisit = new Date(last[0]);
Chrome returns "Invalid Date" but not sure how robust this will be across all browsers if I'm using:
if(lastvisit != "Invalid Date")
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.
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.
ASKER
Just trying to find the best way to detect an invalid date.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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())
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.
IF ( isNAN(lastvisit) == False )
--- VALID DATE