0

I'm trying to convert strings into time_t variables. Here's the code I tried:

#include "pch.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>

using namespace std;

time_t String_to_timet1(string endDate) {
    tm tm = { 0 };
    stringstream ss(endDate);
    ss >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
    time_t epoch = mktime(&tm);

    return epoch;
}

time_t String_to_timet2(string endDate) {
    tm tm = { 0 };
    stringstream ss(endDate);
    ss >> get_time(&tm, "%Y%m%d");
    time_t epoch = mktime(&tm);

    return epoch;
}

int main()
{
    time_t time_certainTime1 = String_to_timet1("2019-01-01 00:00:00");
    cout << time_certainTime1 << endl;

    time_t time_certainTime2 = String_to_timet2("20190101");
    cout << time_certainTime2 << endl;

    return 0;
}

I expected that the results would be the same, but when I run the code with Visual Studio 2017, the results are:

1546268400
-1

and when I run the same code on https://www.onlinegdb.com/online_c++_compiler, the results are:

1546300800
1546300800

Question: Why does Visual Studio give me -1 when it gets a "%Y%m%d" typed string (when the online compiler gives me the result I expected)? How to make a time_t variable with such format?

maynull
  • 1,936
  • 4
  • 26
  • 46
  • `mktime()` returns -1 if the `tm` can't be represented as a `time_t`. You are not doing any error checking to make sure `std::get_time()` is successful – Remy Lebeau Dec 13 '19 at 01:13
  • Unrelated: C++20 has some new tools to handle this. If you can't wait, here's [Howard Hinnant's "Prototype" of the coming additions](https://github.com/HowardHinnant/date). – user4581301 Dec 13 '19 at 01:25

1 Answers1

0

In the documentation for both %m and %d it says leading zeros permitted but not required. This means that it's actually underspecified if it will work without separators or not.

sp2danny
  • 7,488
  • 3
  • 31
  • 53