A quick way to get time_t from the string YYYYMMDDHHMMSS

It is legal? I am trying to get to time_t as quickly as possible by setting a string formatted as YYYYMMDDHHMMSS.

static time_t ConvertToSecSince1970(char *szYYYYMMDDHHMMSS)
{
struct tm    Tm;    

    memset(&Tm, 0, sizeof(Tm));
    Tm.tm_year = makeInt(szYYYYMMDDHHMMSS +  0, 4) - 1900;
    Tm.tm_mon  = makeInt(szYYYYMMDDHHMMSS +  4, 2) - 1;
    Tm.tm_mday = makeInt(szYYYYMMDDHHMMSS +  6, 2);
    Tm.tm_hour = makeInt(szYYYYMMDDHHMMSS +  8, 2);
    Tm.tm_min  = makeInt(szYYYYMMDDHHMMSS + 10, 2);
    Tm.tm_sec  = makeInt(szYYYYMMDDHHMMSS + 12, 2);
    return mktime(&Tm);
}

It seems to give the same answer if I created TM using:

strptime(szYYYYMMDDHHMMSS, "%Y%m%d%H%M%S", &Tm);

I worry that tm_yday, tm_wday, tm_isdst, tm_gmtoff, tm_zone are important. My dates are UTC, so I decided that gmtoff = 0 and tm_zone = 0 could work.

By the way, here is makeInt:

inline int makeInt(const char *p, int size)
{
    const char *endp;
    int intval = 0;

    endp = p + size;
    while (p < endp)
    {
        intval = intval * 10 + *p - '0';
        p++;
    }
    return intval;
}
+3
source share
3 answers

mktime()ignores fields tm_wdayand tm_ydaycalculates new values ​​for them based on other fields. The same applies to BSD extensions tm_gmtoffand tm_zone, except that they are calculated from the local time zone.

, mktime() , UTC, , - UTC, UTC.

+2

, , getdate, , . , , , .

+4

, strptime() , . strptime() , - , strptime(),

  • , time_t ( ), , .

  • Do not work with timestamps in string form. For instance. pass the value of time_t (containing seconds since the appearance of Epoch as a time-returned ()) and convert it only to a string when / if you need to print it / show it to user /.

+1
source

All Articles