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:
// 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; } |
Output:
327