0

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;
}

MS Docs:

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.

rfg
  • 1,331
  • 1
  • 8
  • 24
  • Windows is not the only OS that uses the Unix Epoch as the basis for `time_t` values and time-handling. Dealing with date/time calculations in a portable manner is a *lot* trickier than you think. – Mark Benningfield Apr 19 '19 at 20:40

1 Answers1

0
void second_calculate()
{

    //47 year       ------>1970+47=2017
    //12 day        ------>12 leap year   29 february!!
    //test=0        ------> 00:00:00 01.01.1970   

    int _sec = 1;
    int _min = 60;
    int _hour = 60 * 60;
    int _day = 24 * 60 * 60;
    int _year = 365 * 24 * 60 * 60;


    long long test = 
        47   * _year            //  1970 +47  ---->  2017 
        + 12 * _day             //  leap year ---->  47/4 
        + 40 * _day             //  new year +40 day ---->  february 10
        + 22 * _hour            //  evening  22:00:00 
           +0* _min             //  
           +0* _sec;            //  



    //grennwich
    tm* ptm3 = gmtime(&test);
    printf("date: %s\n", asctime(ptm3));    //22:00:00 10.02.2017 


}