Find number of days between two given dates | A date has day ' d ' , month ' m ' and year ' y ' ; To store number of days in all months from January to Dec . ; This function counts number of leap years before the given date ; Check if the current year needs to be considered for the count of leap years or not ; An year is a leap year if it is a multiple of 4 , multiple of 400 and not a multiple of 100. ; This function returns number of days between two given dates ; initialize count using years and day ; Add days for months in given date ; Since every leap year is of 366 days , Add a day for every leap year ; SIMILARLY , COUNT TOTAL NUMBER OF DAYS BEFORE ' dt2' ; return difference between two counts ; Driver code ; Function call
class Date { constructor ( d , m , y ) { this . d = d ; this . m = m ; this . y = y ; } } let monthDays = [ 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] ; function countLeapYears ( d ) { let years = d . y ; if ( d . m <= 2 ) { years -- ; } return Math . floor ( years / 4 ) - Math . floor ( years / 100 ) + Math . floor ( years / 400 ) ; } function getDifference ( dt1 , dt2 ) { let n1 = dt1 . y * 365 + dt1 . d ; for ( let i = 0 ; i < dt1 . m - 1 ; i ++ ) { n1 += monthDays [ i ] ; } n1 += countLeapYears ( dt1 ) ; let n2 = dt2 . y * 365 + dt2 . d ; for ( let i = 0 ; i < dt2 . m - 1 ; i ++ ) { n2 += monthDays [ i ] ; } n2 += countLeapYears ( dt2 ) ; return ( n2 - n1 ) ; } let dt1 = new Date ( 1 , 2 , 2000 ) ; let dt2 = new Date ( 1 , 2 , 2004 ) ; document . write ( " " + getDifference ( dt1 , dt2 ) ) ;