I want to use mktime
to add days to my date. Code taken from here, tm struct initialization from here. This code woks on Linux (gcc):
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
struct tm t = { 0 };
t.tm_mday += 40;
time_t try1 = mktime(&t);
/* show result */
printf("%d %d %d %d %s", t.tm_year, t.tm_mon, t.tm_mday, try1, ctime(&try1));
return 0;
}
The program returns expected: 0 1 9 2089348096 Fri Feb 9 00:00:00 1900
However when I compile the same code on Windows using
GNU C11 (Rev4, Built by MSYS2 project) version 5.2.0 (x86_64-w64-mingw32) compiled by GNU C version 5.2.0, GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3
I get this output: 0 0 40 -1 (null)
.
How can I add days to dates on Windows?
UPDATE. Turns out mktime on windows works only if the effective date is after Jan 1 1970. Hilarious. Here's a small example:
int main(int argc, char **argv)
{
struct tm t = { 0 };
t.tm_year = 70;
t.tm_mday = 1;
t.tm_mday += 40;
time_t try1 = mktime(&t);
/* show result */
printf("%d %d %d %d %s", t.tm_year, t.tm_mon, t.tm_mday, try1, ctime(&try1));
return 0;
}
The range of the _mkgmtime32 function is from midnight, January 1, 1970, UTC to 23:59:59 January 18, 2038, UTC. The range of _mkgmtime64 is from midnight, January 1, 1970, UTC to 23:59:59, December 31, 3000, UTC. An out-of-range date results in a return value of -1. The range of _mkgmtime depends on whether _USE_32BIT_TIME_T is defined. If not defined (the default) the range is that of _mkgmtime64; otherwise, the range is limited to the 32-bit range of _mkgmtime32.
The question still stands. Is there any way to add days to dates independent of OS? Preferably not limited to after Jan 1 1970.