Monday, January 21, 2019

Date Difference program in c


const int monthDays[12] = {31, 28, 31, 30, 31, 30,
                           31, 31, 30, 31, 30, 31};
int countLeapYears(Date d)
{
    int years = d.year;
  
    // Check if the current year needs to be considered
    // for the count of leap years or not
    if (d.month <= 2)
        years--;
  
    return years / 4 - years / 100 + years / 400;
}


int difference_in_dates(Date *date1, Date *date2)
{
  
    long int n1 = date1->year*365 + date1->day;
  
    for (int i=0; i<date1->month - 1; i++)
        n1 += monthDays[i];
  
    n1 += countLeapYears(date1);
  

    long int n2 = date2->year*365 + date2->day;
    for (int i=0; i<date2->month - 1; i++)
        n2 += monthDays[i];
    n2 += countLeapYears(date2);
  
    // return difference between two counts
    return (n2 - n1);
}
  

No comments:

Post a Comment