0

Why is forward conversion from time_t, equaled to 1, to tm valid, whereas backward is not?

#include <ctime>
#include <map>
using namespace std;
int main() {

    time_t timer = 1;
    tm *timerSt = gmtime(&timer);
    cout << asctime(timerSt) << endl;   //Thu Jan 01 00:00:01 1970
    timer = mktime(timerSt);
    cout <<"timer 0: "<< timer << endl; //timer 0: -1
}
Max Popov
  • 357
  • 2
  • 12
  • 1
    `mktime` assumes local time, not UTC time; it's the inverse of `localtime`, not `gmtime`. Presumably, your time zone is ahead of UTC, so midnight 1970-1-1 local time is before 1970-1-1 UTC, and is not representable in `time_t` – Igor Tandetnik Jun 26 '21 at 17:53
  • @IgorTandetnik Yes, I'm in Ukraine. So how can I mend it? There must be appropriate function. Isn't it? – Max Popov Jun 26 '21 at 17:58
  • 1
    Some implementations offer [`mkgmtime`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/mkgmtime-mkgmtime32-mkgmtime64) or [`timegm`](https://man7.org/linux/man-pages/man3/timegm.3.html), but it's non-standard. See also [How to convert a UTC date & time to a `time_t` in C++?](https://stackoverflow.com/q/12353011) – Igor Tandetnik Jun 26 '21 at 18:05
  • That is much better: timer = _mkgmtime(timerSt); It is giving an anticipated 1. – Max Popov Jun 26 '21 at 19:09

0 Answers0