Year 2038 long int on Windows
The POSIX epoch time is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Operations involving POSIX epoch time, particularly on Windows, may run into Year 2038 problems if “long” type is used to store the epoch time in seconds. The “long” int type only guarantees 32-bit integers, which can store values up to 2,147,483,647. The maximum value that can be stored in a 32-bit signed integer is 2,147,483,647, which corresponds to 03:14:07 UTC on Tuesday, 19 January 2038. After this time, a 32-bit “long” value will overflow, which can cause unexpected behavior in applications that rely on the epoch time. To avoid this problem in a cross-platform compatible manner, consider the explicit 64-bit integer type int64_t to store the epoch time in programs written in C, C++ or likewise in other code languages to store POSIX epoch time. We chose “int64_t” instead of “long long” to be explicit about the integer size needed and useful, which is a general best practice in C / C++.
Example using std::difftime
to calculate the difference between two time points:
#include <cstdint>
#include <ctime>
#include <string>
#include <iostream>
int main() {
std::time_t t1 = 0;
std::time_t t2 = 2147483648; // 03:14:08 UTC on Tuesday, 19 January 2038
std::string posix = std::to_string(static_cast<std::int64_t>(std::difftime(t2, t1)));
std::cout << "POSIX time difference: " << posix << " seconds\n";
return 0;
}