The Program in C++ to Count Number of Days between two given dates is given below:
#include <iostream>
#include <cmath>
using namespace std;
bool isLeap(int year) {
return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
}
int daysInMonth(int year, int month) {
switch (month) {
case 2:
return (isLeap(year)) ? 29 : 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
int daysSince1900(int year, int month, int day) {
int days = 0;
for (int i = 1900; i < year; i++) {
days += 365 + isLeap(i);
}
for (int i = 1; i < month; i++) {
days += daysInMonth(year, i);
}
days += day - 1;
return days;
}
int main() {
int year1, month1, day1;
cout << "Hello Codeauri Family,Enter the first date here (YYYY MM DD): ";
cin >> year1 >> month1 >> day1;
int year2, month2, day2;
cout << "Hello Codeauri Family,Enter the Second date here (YYYY MM DD): ";
cin >> year2 >> month2 >> day2;
int days1 = daysSince1900(year1, month1, day1);
int days2 = daysSince1900(year2, month2, day2);
int difference = abs(days2 - days1);
cout << "Well, the Number of days between " << year1 << "-" << month1 << "-" << day1;
cout << " and " << year2 << "-" << month2 << "-" << day2 << ": ";
cout << difference << endl;
return 0;
}
Output:
Hello Codeauri Family,Enter the first date here (YYYY MM DD): 2023
01
01
Hello Codeauri Family,Enter the Second date here (YYYY MM DD): 1999
08
08
Well, the Number of days between 2023-1-1 and 1999-8-8: 8547
Pro-Tips💡
This program uses the isLeap
and daysInMonth
functions to determine the number of days in a month and whether a year is a leap year, respectively.
The daysSince1900
function calculates the number of days between a given date and January 1, 1900.
The main
function takes in the two dates and uses these functions to calculate the number of days between the two dates,
which is the absolute value of the difference between the number of days since January 1, 1900 for each date.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.