Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 958
PJPS Avatar asked Oct 24 '25 01:10

PJPS


1 Answers

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

like image 57
kennebec Avatar answered Oct 25 '25 17:10

kennebec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!