In this article, we will see how you can Count the days between two dates in C++.
Code:
In this code, the countLeapYears() function will check whether the given date is a leap year or not by checking the year
- is a multiple of 4
- multiple of 400 and not a
- multiple of 100.
and the getDifference() function returns the number of days between the given two dates.
#include <iostream>
using namespace std;
struct Date {
int d, m, y;
};
// storing all month days from January to December
const int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int countLeapYears(Date d)
{
int years = d.y;
// Checking if the current year is leap year or not
if (d.m <= 2)
years--;
return years / 4 - years / 100 + years / 400;
}
int getDifference(Date date1, Date date2)
{
// Before first date count total number of days
long int n1 = date1.y * 365 + date1.d;
// Add days for months in given date
for (int i = 0; i < date1.m - 1; i++)
n1 += monthDays[i];
// Adding a day for every leap year
n1 += countLeapYears(date1);
//count total number of days between first and second date
long int n2 = date2.y * 365 + date2.d;
for (int i = 0; i < date2.m - 1; i++)
n2 += monthDays[i];
n2 += countLeapYears(date2);
return (n2 - n1);
}
int main()
{
Date date1 = { 1, 2, 2024 };
Date date2 = { 1, 3, 2024 };
cout << "Difference between two dates is " << getDifference(date1, date2);
return 0;
}
Output:
Difference between two dates is 29