This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

mktime not accounting for leap year

All,

  I am running mktime based on a GPS time I am receiving.  I check the tm struct values and they are all correct.  When I check the return value in epoch seconds it is off by 1 day.  Also, for the tm.year, it is current year - 1970, not 1900.  Is anyone else having this issue?

Thanks,

Will

  • So this explains why the value to subtract is 1970 and not 1900.  It still doesn't account for why the mktime function does not account for leapyear this year.

    Thanks,

    Will

  • Could you please post a short test case demonstrating the problem, showing the values you are passing to mktime and the return value?

  • void getUbloxUTCTime(unsigned char* utcTimeBuff, unsigned int *time_sec, int *time_mSec, int *time_nSec)

    {

    struct tm time_struct;

    unsigned short year = 0;

    time_struct.tm_sec = utcTimeBuff[NAVTIME_SEC_OFFSET];

    time_struct.tm_min = utcTimeBuff[NAVTIME_MIN_OFFSET];

    time_struct.tm_hour = utcTimeBuff[NAVTIME_HOUR_OFFSET];

    time_struct.tm_mday = utcTimeBuff[NAVTIME_DAY_OFFSET];

    time_struct.tm_mon = utcTimeBuff[NAVTIME_MONTH_OFFSET] - 1;

    memcpy(&year, &utcTimeBuff[NAVTIME_YEAR_OFFSET], sizeof(short));

    time_struct.tm_year = year - 1970;

    time_struct.tm_isdst = 0;

    *time_sec = mktime(&time_struct);

    memcpy(time_nSec, &utcTimeBuff[NAVTIME_NANO_OFFSET], sizeof(time_nSec));

    *time_mSec = abs(*time_nSec) / 1000000;

    }

    Input:

    tm_sec 33

    tm_min 12

    tm_hour 13

    tm_mday  22

    tm_mon 4

    tm_year 42

    tm_wday 0

    tm_yday 0

    tm_isdst 0

    Output:

    time_sec = 1337605953

    Converting time_sec gives Mon, 21 May 2012 13:12:33 UTC

     

  • I believe TI's mktime does not account for the day once past FEB 29 if we are within the leapyear.  Everything was fine until passing FEB 29.

    THanks,

    Will

  • mktime is messing up leap years because it starts computing them from 1900 because it assumes year 0 is 1900, and your code assumes year 0 is 1970.  The tm_year field in mktime uses an epoch of 1900, as required by the C standard, so you can't use 1970 as the bias. You must use 'year - 1900' as the value of tm_year. Then, if you want to convert the return value to the POSIX 1970-biased number of seconds, subtract 2208988800L seconds (the number of seconds from midnight January 1, 1900 to the POSIX epoch, as defined in RFC 868).