Possible bug in std::get_time and std::chrono::system_clock::from_time_t

Hi,

I have a problem that I was unable to find anything on in LLVM Bugzilla. Consider this code:

auto stringToTime(std::string const & TimeString) {
  std::tm t;
  std::istringstream InSS(TimeString);
  InSS >> std::get_time(&t, "%Y-%m-%d %T");
  auto Temp = std::mktime(&t);
  std::cout << "Temp: " << Temp << std::endl;
  return std::chrono::system_clock::from_time_t(Temp);
}
int main() {
  stringToTime("1996-02-25 12:13:13");
  stringToTime("1996-02-25 12:13:13”);
  return 0;
}

It produces the following output:
Temp: 825243193
Temp: 825246793

The last timestamp is correct whereas the first timestamp is off by one hour (3600s).

Removing the last line ("return std::chrono::system_clock::from_time_t(Temp);”) makes the two output lines identical (and correct).

I am using MacOSX Mojave 10.14.6 as a development OS. The compiler version string is: "Apple LLVM version 10.0.1 (clang-1001.0.46.4)”. The region (in System preferences) is set to Sweden.

Is this a known issue?

/Jonas

I'm not able to reproduce your exact result with different values
printed by the two statements, but I do get different results
depending on whether I build with -O2 or not :slight_smile:

I think the problem is hinted at by this note on
https://en.cppreference.com/w/cpp/io/manip/get_time
"Note: tm_isdst is not written to, and needs to be set explicitly for
use with functions such as mktime"

With that fixed, the program seems to work as expected:

#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

auto stringToTime(std::string const & TimeString) {
  std::tm t;
  std::istringstream InSS(TimeString);
  InSS >> std::get_time(&t, "%Y-%m-%d %T");
  t.tm_isdst = -1; // <---- Fix here.
  auto Temp = std::mktime(&t);
  std::cout << "Temp: " << Temp << std::endl;
  return std::chrono::system_clock::from_time_t(Temp);
}
int main() {
  stringToTime("1996-02-25 12:13:13");
  stringToTime("1996-02-25 12:13:13");
  return 0;
}

I find it slightly weird that a seemingly unrelated code change makes this work or not work on my machine. Regardless, you are entirely correct as to the root cause of the problem. Thanks for the help!

/Jonas