tags:

views:

3204

answers:

5

I have an issue -

The javascript Date("mm-dd-yyyy") constructor doesn't work for FF. It works fine for IE. IE : new Date("04-02-2008") => "Wed Apr 2 00:00:00 EDT 2008" FF2 : new Date("04-02-2008") => Invalid Date

So lets try another constructor: Trying this constructor Date("yyyy", "mm", "dd") IE : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008" FF : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008" IE : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008" FF : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008"

So the Date("yyyy", "mm", "dd") constructor uses an index of 0 to represent January.

Has anyone dealt with this?
There must be a better way than subtracting 1 from the months.

+5  A: 

I've always found the Javascript Date implementation to be frustrating, until I found this.

leek
Yeap, that thing is awesome.
Braveyard
+10  A: 

It is the definition of the Date object to use values 0-11 for the month field.

I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters.

BTW, in Firefox,

new Date("04/02/2008");

works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead:

new Date(2008, 3, 2);
matt b
A: 

Bold statement.

This might have your interest: JavaScript Pretty Date.

roosteronacid
A: 

You're quite right, month is indicated as an index, so January is month number 0 and December is month number 11 ...

-- and there is no work-around as it is stated clearly in the ECMA-script-definition, though simple tricks commonly will work:

var myDate = "2008,03,02".split(",");
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); 
alert(theDate);
roenving
+1  A: 

nice trick indeed, which i just found out the hard way (by thinking thru it). But i used a more natural date string with hyphen :-)

var myDateArray = "2008-03-02".split("-");
var theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]); 
alert(theDate);
joedotnot