# Find number of days between two given dates in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two arrays date1[] and date2 consisting of 3 integers which denote the DD-MM-YYYY of daes. Our task is to find the number of days between two given dates.

Let’s take an example to understand the problem,

## Input

date1[] = {13, 3, 2021}, date2[] = {24, 5, 2023}

## Output

802

## Explanation

The difference is 2 years , 2 months (3 - 5) and 11 days.

2*356 + (30 + 31) + 11 = 802

## Solution Approach

A simple solution to the problem is by looping, starting from the start date date1 to date2 counting the number of days. And returning the value. This approach is ok, but a more efficient approach can be there.

## Efficient Approach

A more efficient approach to the problem is by counting the total number of days till both the dates date1[] and date2[]. And then the absolute difference between both gives the result.

To count the number of days till both date1[] from 01/01/0000.

## YEAR

Number of days till the first day of the year date1

Number of days = 365*(years) + no. of leap year

## MONTH

For a number of days till the 1st day of the month. Count from month array.

Number of days = monthDays[date].

monthDays will store the total number of days till the 1st date of the month.

## DATE

Number of days.

Sum of all these gives the count of days till date date1[]. The difference between the counts is the result.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
#include <math.h>
using namespace std;
const int monthDays = { 31, 59, 90, 120, 151, 181, 212, 243,
273, 304, 334, 365 };
int countLeapYearDays(int d[]){
int years = d;
if (d <= 2)
years--;
return ( (years / 4) - (years / 100) + (years / 400) );
}
int countNoOfDays(int date1[], int date2[]){
long int dayCount1 = (date1 * 365);
dayCount1 += monthDays[date1];
dayCount1 += date1;
dayCount1 += countLeapYearDays(date1);
long int dayCount2 = (date2 * 365);
dayCount2 += monthDays[date2];
dayCount2 += date2;
dayCount2 += countLeapYearDays(date2);
return ( abs(dayCount1 - dayCount2) );
}
int main(){
int date1 = {13, 3, 2021};
int date2 = {24, 5, 2023};
cout<<"The number of days between two dates is "<<countNoOfDays(date1, date2);
return 0;
}

## Output

The number of days between two dates is 802