Write a C program to find the number of days between two given dates.
int daysInMonth[] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
/* given year is leap year or not */
int isLeapYear(int year) {
int flag = 0;
if (year % 100 == 0) {
if (year % 400 == 0) {
flag = 1;
} else {
flag = 0;
}
} else if (year % 4 == 0) {
flag = 1;
}
return flag;
}
int main() {
int year, month, date, days = 0, i;
int cyear, cmonth, cdate, tmpMon, tmpYear;
char str[100];
/* get From date from the user */
printf("From date(dd:mon:year):\n");
fgets(str, 100, stdin);
sscanf(str, "%d:%d:%d", &date, &month, &year);
/* get To date from the user */
printf("To date(dd:mon:year):\n");
fgets(str, 100, stdin);
sscanf(str, "%d:%d:%d", &cdate, &cmonth, &cyear);
tmpMon = month;
tmpYear = year;
/* if From & To date are from same month and year */
if (cyear == year && cmonth == month) {
days = cdate - date + 1;
printf("No of days: %d\n", days);
return 0;
}
/* From month is feb - add additional 1 day if leap year */
if (month == 2) {
days = daysInMonth[month - 1] - date + 1 + isLeapYear(year);
} else {
days = daysInMonth[month - 1] - date + 1;
}
/* From month is feb - move forward to next year and month to Jan */
if (month == 12) {
month = 0;
year++;
}
while (year <= cyear) {
for (i = month; i < 12; i++) {
if ((year == cyear) && (i == cmonth - 1)) {
/* To date's month and year */
days = days + cdate;
break;
}
if (i == 1) {
/* leap year validation for feb month */
days = days + daysInMonth[i] + isLeapYear(year);
} else {
days = days + daysInMonth[i];
}
}
month = 0;
year++;
}
/* print the results */
printf("No of days from %02d:%02d:%d to %02d:%02d:%d is %d\n",
date, tmpMon, tmpYear, cdate, cmonth, cyear, days);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
From date(dd:mon:year):
13:12:1991
To date(dd:mon:year):
23:06:2013
No of days from 13:12:1991 to 23:06:2013 is 7864
From date(dd:mon:year):
13:12:1991
To date(dd:mon:year):
23:06:2013
No of days from 13:12:1991 to 23:06:2013 is 7864
No comments:
Post a Comment