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[2]

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[1]].

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[12] = { 31, 59, 90, 120, 151, 181, 212, 243,
273, 304, 334, 365 };
int countLeapYearDays(int d[]){
   int years = d[2];
   if (d[1] <= 2)
      years--;
   return ( (years / 4) - (years / 100) + (years / 400) );
}
int countNoOfDays(int date1[], int date2[]){
   long int dayCount1 = (date1[2] * 365);
   dayCount1 += monthDays[date1[1]];
   dayCount1 += date1[0];
   dayCount1 += countLeapYearDays(date1);
   long int dayCount2 = (date2[2] * 365);
   dayCount2 += monthDays[date2[1]];
   dayCount2 += date2[0];
   dayCount2 += countLeapYearDays(date2);
   return ( abs(dayCount1 - dayCount2) );
}
int main(){
   int date1[3] = {13, 3, 2021};
   int date2[3] = {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
raja
Published on 15-Mar-2021 15:21:12
Advertisements