C++ Exercises: Count the number of days between two given dates
C++ Date: Exercise-6 with Solution
Write a C++ program to count the number of days between two given dates.
Sample Solution:
C++ Code:
#include <iostream>
#include <string>
using namespace std;
bool is_leap_year(int y) {
return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);
}
int days_in_month(int m, int y) {
if (m == 4 || m == 6 || m == 9 || m == 11)
return 30;
else if (m == 2)
return is_leap_year(y) ? 29 : 28;
else
return 31;
}
int days_Between_dates(string date) {
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));
int result = day;
for (int yy = 1971; yy < year; yy++)
result += is_leap_year(yy) ? 366 : 365;
for (int mm = 1; mm < month; mm++)
result += days_in_month(month, year);
return result;
}
int main() {
cout << "Date Format -> YYYY-MM-DD" << endl;
cout << "\nDays between 2022/01/31 to 2022/01/01 = " << abs(days_Between_dates("2022/01/31") - days_Between_dates("2022/01/01")) << endl;
cout << "\nDays between 2000/01/31 to 2019/02/01 = " << abs(days_Between_dates("2019/02/01") - days_Between_dates("2000/01/31")) << endl;
cout << "\nDays between 1980/05/31 to 1995/12/12 = " << abs(days_Between_dates("1995/12/12") - days_Between_dates("1980/05/31")) << endl;
}
Sample Output:
Date Format -> YYYY-MM-DD Days between 2022/01/31 to 2022/01/01 = 30 Days between 2000/01/31 to 2019/02/01 = 6938 Days between 1980/05/31 to 1995/12/12 = 5677
Flowchart:

C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Number of days of a month from a given year and month
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join