给定两个表示两个日期的字符串str1和str2 ,任务是计算给定两个日期之间的天数。鉴于给出的日期是1971年以后。
例子:
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
方法:想法是将两个日期都转换成各自的秒数。由于一天中有86,400秒,因此两天之间的天数可以通过将秒数之差除以86,400来得出。
下面是上述方法的实现:
// C++ implementation of the above approach
#include
#include
#include
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;
}
输出:
327