0

I've build a function which checks if a date parts values are valid :

Bad value example :

new Date(2012,3,44) = 
Mon May 14 2012 00:00:00 GMT+0300 (Jerusalem Daylight Time)

Here is the function ( its arguments are being sent by me separately !)

function isDate(year, month, day)
{
   ...
}

alert(isDate( 2001,2,29));

However , I have a problem.

If I have an invalid date object like : var t= new Date(2001,2,44) : And I want to send it to my function , I need to extract its values.

How can I extract the 44 value + 2 value ?

t.getDate() //13
t.getMonth() //3   (days went from march to april)

any help ?

4

1 回答 1

5

You can't extract the value 44 from the Date object, because it's not there.

When creating a Date object with out of range values, the values will be adjusted so that it becomes a valid date.

The components of a Date object always forms a valid date. If you want to check if the values are valid, you have to do that before creating the Date object, or use the Date object to check them:

var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
  // components were valid
}
于 2012-09-02T09:32:55.523 回答