views:

26

answers:

1

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  A: 

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).

bobince
I'm using Safari 5 on WinXP. And yes, it's parsing dates that are generated by code, not by the user, so i'm not worried about that side of things.
Chris
I ended up changing my code so that if it was an empty string, assume that it's an invalid date (as well as the isNaN test)
Chris
Ah, you're right, this is a new behaviour in Safari 5 only. How very strange... ah well, that's just another wart to add to the long list of date-parsing weirdness. Manual checking is definitely called-for.
bobince