4

I realize that this probably a feature, but I need the Date Constructor to bail on an invalid date not automagically roll it to the appropriate date. What is the best way to accomplish this?

new Date('02/31/2015');

becomes

Tue Mar 03 2015 00:00:00 GMT-0500 (EST)

Sorry if this has already been asked, I wasn't able to/am too stupid to find it :).

1
  • 1
    Parse date strings yourself. Commented Feb 24, 2015 at 21:23

4 Answers 4

2

If you can count on the string input being formatted as digits (no weekday or month names), you can look at the input before creating a Date object.

function validDate(s){
    //check for day-month order:
    var ddmm= new Date('12/6/2009').getMonth()=== 5;

    //arrange month,day, and year digits:

    var A= s.split(/\D+/).slice(0, 3), 
    month= ddmm? A[1]: A[0], 
    day= ddmm? A[0]: A[1], 
    y= A.pop(), 

    //figure february for given year:

    feb= y%4== 0 && (y%100 || y%400== 0)? 29: 28, 

    // set maximum days per month:

    mdays= [0, 31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    //if the string is a valid calendar date, return a date object.
    //else return NaN (or throw an Error):

    return mdays[parseInt(month, 10)]-A[1]>= 0? new Date(s): NaN;
}

validDate('02/29/2015')

/* returned value: (Number) NaN */

Sign up to request clarification or add additional context in comments.

Comments

2

It seems that you cannot force a failure on illegal dates. The MDN docs claim, the observed behaviour should only happen when the constructor is called with more than 1 argument, but this condition does not appear to hold (at least it doesn't on chrome 40).

However, you can re-convert the Date and compare it with the original string:

var s = '02/31/2015';
var d = new Date(s)
var s_re = d.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' } );
if (s === s_re) {
    // ok
}

Comments

2

I ended up using moment.js. It has validation and overflow calculations among other Date object enhancements. Thanks to Kevin Williams for

1 Comment

For those reading this answer sever years later, note that the moment.js library is no longer being supported and people should find other libraries for managing dates/times.
-2

You can't set a JavaScript Date object to an invalid date.

Nevertheless you may want to check if a date is invalid.

2 Comments

mydate.setTime(NaN)
Isn't Feb 31 invalid? Because I can send it to the date constructor. Not that I don't believe you, I just don't understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.