Finding number of days between two dates using StringStream

Given two strings str1 and str2 which represent two dates, the task is to count the number of days between given two dates. Given that dates given are beyond 1971.

Examples:

Input: str1 = “2020-01-29”, str2 = “2020-01-30”
Output: 1
Explanation:
The number of days between 29th January and 30th January is 1.

Input: str1 = “1971-06-29”, str2 = “2019-06-23”
Output: 17526

Approach: The idea is to convert both the dates into its respective seconds. Since there are 86, 400 seconds in a day, the number of days between both the days can be found out by dividing the difference of seconds with 86, 400.



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
  
// Function to find the number of days
// between given two dates
int daysBetweenDates(string date1, string date2)
{
    stringstream ss(date1 + "-" + date2);
    int year, month, day;
    char hyphen;
  
    // Parse the first date into seconds
    ss >> year >> hyphen >> month >> hyphen >> day;
    struct tm starttm = { 0, 0, 0, day,
                          month - 1, year - 1900 };
    time_t start = mktime(&starttm);
  
    // Parse the second date into seconds
    ss >> hyphen >> year >> hyphen
        >> month >> hyphen >> day;
    struct tm endtm = { 0, 0, 0, day,
                        month - 1, year - 1900 };
    time_t end = mktime(&endtm);
  
    // Find out the difference and divide it
    // by 86400 to get the number of days
    return abs(end - start) / 86400;
}
  
// Driver code
int main()
{
    string str1 = "2019-09-12";
    string str2 = "2020-08-04";
    cout << daysBetweenDates(str1, str2);
    return 0;
}

chevron_right


Output:

327

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.