简体   繁体   中英

Javascript date validation from current date to before 3 years

I am new to javascript and request help.I have two dates start date and end date on my page. I want to throw a validation error through javascript if the user picks 3 years before the current date for the start date and 3 years after the current date for the end date.

How should I handle this? I tried the following,

var a1 = Date.parse(startDate);
var b1 = Date.parse(endDate);
var mydate=new Date();    
var c1 = Date.parse(mydate);    
var diff1 = c1-a1;
var daysCal1 = diff1 / 1000 / 60 / 60 / 24;
var days1 = Math.ceil(daysCal1);
if (days1 > 1095) {         
      //throw the exception

}   

Well, assuming you've stored the start date as a1 and end date as b1, you could use the *.valueOf() for date objects for your comparison (see http://www.w3schools.com/jsref/jsref_valueof_date.asp )

So you could do something along the lines of:

var currentDate = new Date();
var currentMinus = currentDate.valueOf()-(3*365.25*24*60*60*1000); //or use +94672800000 
var currentPlus = current.Date.valueOf()+94672800000;
if (a1.valueOf() < currentMinus) {
    //should execute if a1 is more than 3 years prior to current date/time
}
if (b1.valueOf() > currentPlus) {
    //should execute if b1 is more than 3 years after current date/time
}

I didn't test all of this as is, but should work for you or at least give you the concepts to use in your own code/situation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM