Copy codeThe Code is as follows:
// Determine whether it is a leap year
Function isLeapYear (year ){
If (year % 4 = 0 & (year % 100! = 0) | (year % 400 = 0 )))
{
Return true;
}
Return false;
}
// Judge the two dates before and after
Function validatePeriod (fyear, fmonth, fday, byear, bmonth, bday ){
If (fyear <byear ){
Return true;
} Else if (fyear = byear ){
If (fmonth <bmonth ){
Return true;
} Else if (fmonth = bmonth ){
If (fday <= bday ){
Return true;
} Else {
Return false;
}
} Else {
Return false;
}
} Else {
Return false;
}
}
// Calculate the difference between the two dates
Function dateDiff (d1, d2 ){
Var disNum = compareDate (d1, d2 );
Return disNum;
}
Function compareDate (date1, date2)
{
Var regexp =/^ (\ d {1, 4}) [-| \.] {1} (\ d {1, 2}) [-| \.] {1} (\ d {1, 2}) $ /;
Var monthDays = [,];
Regexp. test (date1 );
Var date1Year = RegExp. $1;
Var date1Month = RegExp. $2;
Var date1Day = RegExp. $3;
Regexp. test (date2 );
Var date2Year = RegExp. $1;
Var date2Month = RegExp. $2;
Var date2Day = RegExp. $3;
If (validatePeriod (date1Year, date1Month, date1Day, date2Year, date2Month, date2Day )){
FirstDate = new Date (date1Year, date1Month, date1Day );
SecondDate = new Date (date2Year, date2Month, date2Day );
Result = Math. floor (secondDate. getTime ()-firstDate. getTime ()/(1000*3600*24 ));
For (j = date1Year; j <= date2Year; j ++ ){
If (isLeapYear (j )){
MonthDays [1] = 2;
} Else {
MonthDays [1] = 3;
}
For (I = date1Month-1; I <date2Month; I ++ ){
Result = result-monthDays [I];
}
}
Return result;
} Else {
Alert ('Sorry, the first time must be earlier than the second time. Thank you! ');
Exit;
}
}
Call this function to pass two time values: 2013-01-19 2013-12-19
Days = dateDiff (d1, d2 );