user1207217
user1207217

Reputation: 557

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?

Upvotes: 1

Views: 1118

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218880

For a modern, less error prone way of doing this, here's a free, open-source C++11/14/17 library to do the same thing, avoiding the error-prone, thread-unsafe C API.

#include "chrono_io.h"
#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    sys_seconds t = sys_days{1_d/dec/1969};
    std::cout << t.time_since_epoch() << '\n';
}

Output:

-2678400s

Upvotes: 3

Daniel
Daniel

Reputation: 528

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)

Upvotes: 2

Related Questions