Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Javascript Date() constructor doesn't work

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...