user1207217 user1207217 - 9 months ago 34
C++ Question

epoch in C++ using mktime

I was reading the following: http://en.cppreference.com/w/cpp/chrono/c/mktime

Which in particular says:


Converts local calendar time to a time since epoch as a time_t object.


I has assumed this epoch is the unix epoch (1970 01 01), but from the following program

#include <ctime>
#include <iostream>

int main()
{
std::tm example = {00, 00, 00, 01, 12, 69};
std::cout << std::mktime(&example) << std::endl;
return 0;
}


I got the output


0


This is telling me that the epoch is at 00:00:00 on 1st December 1969.
Is the epoch implementation defined, or have I some other fundamental misunderstanding?

Answer Source

See here.

tm_mon is defined as month since January [0,11] which makes your 12 months given to std::tm to December + 1 month, so January 1970.

As an example, the year 1968 with 24 months returns 0 as well:

#include <ctime>
#include <iostream>

int main(){
  std::tm example;
  example.tm_sec = 0;
  example.tm_min = 0;
  example.tm_hour = 0;
  example.tm_year = 68;
  example.tm_mon = 24;
  example.tm_mday = 1;

  std::cout << std::mktime(&example) << "\n";
  return 0;
}

Output:

0

(or -3600 because of DST)