class Solution {
public:
int daysBetweenDates(string date1, string date2) {
}
};
I have this function. Suppose I have parameter
date1 = "2020-01-15", date2 = "2019-12-31"
How can i find them as Title? Thank you so much!
CodePudding user response:
Once you parse the date and appropriate month, day, year information is extracted, you can use the <chrono>
header to find the difference in days:
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono;
auto tp1 = sys_days{January / 15 / 2020};
auto tp2 = sys_days{December / 31 / 2019};
std::cout << (tp1 - tp2) << '\n'; // 15d
}
https://godbolt.org/z/hfM8YWze5
CodePudding user response:
Alternatively, a pre-C 20 solution could be the following:
#include <iostream>
#include <chrono>
int main()
{
std::string date1 = "2020-01-15";
std::tm tm1 = {};
strptime(date1.c_str(), "%Y-%m-%d", &tm1);
auto tp1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));
std::string date2 = "2019-12-31";
std::tm tm2 = {};
strptime(date2.c_str(), "%Y-%m-%d", &tm2);
auto tp2 = std::chrono::system_clock::from_time_t(std::mktime(&tm2));
std::chrono::system_clock::duration d = tp1 - tp2;
using DayLength = std::chrono::duration<int,std::ratio<60*60*24>>;
DayLength days = std::chrono::duration_cast<DayLength> (d);
std::cout << days.count() << std::endl;
return 0;
}
I cannot wrap my head enough on how convoluted the date-extraction operation above is, without using C 20 std::chrono::sys_days
.
Basically, it makes the following conversions: string -> C string -> struct tm -> time_point -> duration (in periods) -> duration (in days) -> arithmetic type for printing