Issue
I have written a program which should convert iso 8601
strings into std::chrono::system_clock::time_point
.
But it has sometimes an indeterministic behavior.
If you execute the program multiple times, the parsed timestamps differ by 1 hour.
As far as i know, when you want to convert date-strings(iso 8601
) to std::chrono::system_clock
types, you currently need some functions from ctime (this means, that you need to use c-functions), if you don't want to use external libraries.
So i used strptime(), mktime() and std::tm_t.
Here is the MWE:
#include <chrono>
#include <ctime>
#include <iostream>
#include <sstream>
int main(void) {
std::tm t;
strptime("2016-01-01T00:00:00", "%Y-%m-%dT%H:%M:%S", &t);
auto time = mktime(&t);
std::cout << "UNIX-seconds: " << time << std::endl;
//std::cout << "tm-hours: " << t.tm_hour << ", UNIX-seconds: " << time << std::endl;
auto tp = std::chrono::system_clock::from_time_t(time);
{
std::stringstream ss;
std::chrono::system_clock::to_time_t(tp);
}
}
If you compile it with g++ --std=c++14 main.cpp -o out
and run it multiple times, I get one of the following 2 outputs:
UNIX-seconds: 1451599200
or
UNIX-seconds: 1451602800
But I currently don't know why I get sometimes the first and sometimes the second one.
If you uncomment the commented line, the indeterministic behavior goes away and I get the following line:
tm-hours: 0, UNIX-seconds: 1451602800
What can I do, to get deterministic behavior?
I have debian 8, g++v4.9 and my pc is in timezone Europe/Vienna.
Solution
mktime
respects tm_isdst
member of std::tm
. strptime
does not change that flag and it retais its previous value. As std::tm
is POD, tm_isdst
is not initialized by default construction, so you need to initialize it manually, or you will get indeteminate value.
Answered By - Revolver_Ocelot