PJPS
PJPS

Reputation: 110

How to prevent JavaScript Date Constructor from accepting invalid dates?

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

Upvotes: 4

Views: 1559

Answers (4)

PJPS
PJPS

Reputation: 110

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

Upvotes: 2

collapsar
collapsar

Reputation: 17238

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
}

Upvotes: 2

kennebec
kennebec

Reputation: 104760

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 */

Upvotes: 2

Harijoe
Harijoe

Reputation: 1791

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

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

Upvotes: -2

Related Questions