0

I have achieved weird results with std::mktime on Apple Clang. I have extracted an MCV:

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

std::time_t test()
{
    std::stringstream stream;
    stream << "12:30";
    struct tm tm = {};
    stream >> std::get_time(&tm, "%H:%M");
    std::time_t t = std::mktime(&tm);
    return t;
}

int main()
{
    std::cout << static_cast<long int>(test()) << std::endl;
    return 0;
}

Here I am parsing a string containing a valid time. std::get_time() parses time and saves it to tm object correctly.

std::mktime() always returns -1 on Apple Clang, what indicates an error (but it is impossible to figure out which one exactly). My Clang version:

Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.2.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

I have tested this code on Wandbox, it works correctly with GCC since 5.1.0 and with Clang since 3.2 and prints -2209062600.

Looks like an Apple Clang bug to me.

Oleg Lokshyn
  • 517
  • 7
  • 14
  • Doesn't `errno` tell you what's wrong? – Jesper Juhl Apr 10 '18 at 19:19
  • From the documentation: If the std::tm object was obtained from std::get_time or the POSIX strptime, the value of tm_isdst is indeterminate, and needs to be set explicitly before calling mktime. – Barmar Apr 10 '18 at 19:24
  • @JesperJuhl, no, it equals to 0. As far as I remember, it should be explicitly stated in the standard whether errno reflects the error status of the function, but [cppreference](http://en.cppreference.com/w/cpp/chrono/c/mktime) says nothing about it. – Oleg Lokshyn Apr 10 '18 at 19:25
  • @Barmar, yeah, I have tried setting tm->tm_isdst to 0, -1 and 1 before the call to std::mktime - the result is the same. – Oleg Lokshyn Apr 10 '18 at 19:27
  • Have you tried examining the members of the `tm` struct? – Barmar Apr 10 '18 at 19:29
  • @Barmar, yes, tm structure contains correct values. – Oleg Lokshyn Apr 10 '18 at 19:36
  • Reproduced it here with `Apple LLVM version 8.0.0 (clang-800.0.42.1)` as well. – Barmar Apr 10 '18 at 19:50
  • When I print the members of `tm`, year, month, and day are all 0. – Barmar Apr 10 '18 at 19:57
  • The problem happens when `tm_year` is `0` or `1`. – Barmar Apr 10 '18 at 20:06
  • Related: https://stackoverflow.com/questions/35300453/am-i-using-tm-mktime-wrong-and-if-not-is-there-a-workaround?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Barmar Apr 10 '18 at 20:13

0 Answers0