int daysBetweenDates(struct date d1, struct date d2) { int numDays = 0, i; int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; struct date temp; //sort dates if (d1.year > d2.year) { temp = d1; d1 = d2; d2 = temp; } else if (d1.month > d2.month) { temp = d1; d1 = d2; d2 = temp; } else if (d1.day > d2.day) { temp = d1; d1 = d2; d2 = temp; } //d1 earlier than d2 for (i = d1.year; i < d2.year; i++) { numDays += isLeapYear(i) ? 366 : 365; } numDays -= dayIndex(d1); numDays += dayIndex(d2); return numDays; }
int daysBetweenDates(struct date d1, struct date d2) { int numDays = 0, i; struct date temp; if (d1.year > d2.year) { temp = d1; d1 = d2; d2 = temp; } else if (d1.month > d2.month) { temp = d1; d1 = d2; d2 = temp; } else if (d1.day > d2.day) { temp = d1; d1 = d2; d2 = temp; } for (i = d1.year; i < d2.year; i++) { numDays += isaLeapYear(i) ? 366 : 365; } numDays -= dayIndex(d1); numDays += dayIndex(d2); return numDays; }
int main() { struct date d; int N; printf("Enter a date: "); scanf("%d-%d-%d", &d.year, &d.month, &d.day); if (!validate(d)) { printf("\nInvalid date"); return 0; } printf("\n\nYear: %d", currentYear(d)); printf("\n\nPrevious year: %d", previousYear(d)); printf("\n\nMonth: %d", currentMonth(d)); printf("\n\nMonth name: %s", monthName(d)); printf("\n\nPrevious month name: %s", prevMonthName(d)); printf("\n\nDay: %d", currentDay(d)); printf("\n\nDay name: %s", dayOfWeek(d)); printf("\n\nDay index: %d", dayIndex(d)); printf("\n\nDATE BEFORE N DAYS: "); printf("\nEnter value for N: "); scanf("%d", &N); if (N < 0) { return 0; } struct date before = dateBeforeNDays(d, N); printf("\nDate before N days: %04d-%02d-%02d", before.year, before.month, before.day); printf("\n\nDAYS BETWEEN DATES: "); printf("\nEnter another date: "); struct date d1; scanf("%d-%d-%d", &d1.year, &d1.month, &d1.day); if (!validate(d1)) { printf("\nInvalid date"); return 0; } printf("\nDays between dates: %d days", daysBetweenDates(d, d1)); printf("\n"); return 0; }
struct date dateBeforeNDays(struct date d, int N) { struct date temp; int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (N == 0) { return d; } temp = d; //subtract years int dayInd = dayIndex(d); if (N > dayInd) { N -= dayInd; temp.day = 31; temp.month = 12; temp.year -= 1; dayInd = dayIndex(temp); while (N > dayInd) { temp.year--; N -= dayInd; dayInd = dayIndex(temp); } } //subtract months dayInd = dayIndex(temp); if (N < dayInd) { if (N >= temp.day) { temp.month--; if (temp.month == 0) { temp.month = 12; } N -= temp.day; temp.day = monthDays[temp.month - 1]; if (temp.month == 2) { temp.day += isLeapYear(temp.year); } while (N >= temp.day) { temp.month--; if (temp.month == 0) { temp.month = 12; } N -= temp.day; temp.day = monthDays[temp.month - 1]; if (temp.month == 2) { temp.day += isLeapYear(temp.year); } } } //subtract days if (N < temp.day) { temp.day -= N; } } return temp; }