My application receives a date and time string. I need to be able to parse this string and compare it to the current time in seconds.
I am parsing this as below into a struct tm t
to get the year, month, day, hour, minute, and second separately.
std::string timestr = "2020-12-18T16:40:07";
struct tm t = {0};
sscanf(timestr.c_str(), "%04d-%02d-%02dT%02d:%02d:%02d",
&t.tm_year, &t.tm_mon, &t.tm_mday,
&t.tm_hour, &t.tm_min, &t.tm_sec);
I'm not sure if I need to convert this to epoch time, but when I do , I get -1. I'm not sure why.
time_t t_of_day;
t_of_day = mktime(&t);
Do I actually need to convert this to epoch first?
What is the best way for me to get the current time in seconds and then compare it to the time information I get in t
? Thanks.
You want C++ parsing:
https://en.cppreference.com/w/cpp/io/manip/get_time
std::stringstream timestr = "2020-12-18T16:40:07";
struct tm t = {0};
timestr >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
I should note there is a bug in your code as: tm_year
is not the same as year as we know it. This is the number of years since 1900!
https://www.cplusplus.com/reference/ctime/tm/
So your code needs another line:
t.tm_year -= 1900;
Note: std::get_time()
already does that compensation.
This is probably why mktime()
is returning -1 as the year 3920 is out of range.