How to check if new Date(“some date”) was able to

2019-07-21 04:29发布

问题:

I have the following code, which is supposed to try to parse a given date. If it fails, it defaults to the current date:

var date = new Date(textbox.value); // Try to parse
if (isNaN(date)) date = new Date(); // Default to current

Now i'm using isNaN() to test if it was able to parse correctly, eg to check that new Date() didn't return 'Invalid Date'.

This seems to work fine on IE, FF, and Chrome, but doesn't work on safari. Eg if it tries to parse an empty string for the date, sometimes it think's it's 1970, and sometimes it thinks it's an invalid date. Here's an exerpt from the safari JS console:

a=new Date("")  <-- This thinks it's 1970 for some reason
Thu Jan 01 1970 11:00:00 GMT+1100 (AUS Eastern Daylight Time)

b=new Date("abc") <-- Fails of course, which is good
Invalid Date

c=new Date("") <-- Why does this fail now, whereas it thought it was 1970 before?
Invalid Date

isNaN(a)  <-- Why is it successfully parsing an empty string for a date?
false

isNaN(b)  <-- Fair enough
true

isNaN(c)  <-- This is what i'd expect, but why is it different now?
true

Not sure whats happening here, thanks a lot

回答1:

What Safari? Doesn't happen for me:

> a= new Date('')
Invalid Date
> isNaN(a)
true

on Safari 4.0 (either OS).

In general though JavaScript Date parsing is traditionally largely unspecified and totally unreliable. You don't want to rely on it for user-input values as it'll exhibit inconsistent and often inappropriate behaviour across browsers, platforms and locales. It's usually better to write your own parser (or use one of the existing date libraries, eg. fleegix's).