Question

Is this legit? Im trying to get to a time_t as fast as possible given a string formatted like 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 produce the same answer if I created TM using:

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

I am worried that tm_yday, tm_wday, tm_isdst, tm_gmtoff, tm_zone are important. My dates are UTC so I figured gmtoff = 0 and tm_zone = 0 might 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;
}
Was it helpful?

Solution

mktime() ignores the tm_wday and tm_yday fields, and calculates new values for them based on the other fields. The same applies to the BSD extensions tm_gmtoff and tm_zone, except that they are calculated from the local time zone.

Note however that mktime() uses local time, not UTC, so if your input dates are UTC then your timezone must be set to UTC.

OTHER TIPS

You would probably be better off using getdate unless you are sure it is too slow. Else, what you are doing looks pretty fine if not a slight bit cryptic.

Date and time handling in general has a lot of tricky gotchas, so I'd strongly recommend strptime() rather than rolling your own. If performance of strptime() is a bottleneck, work around it in some other way than trying to create a better strptime(), such as

  1. Your string, as well as time_t (as it's usually used), gives only second accuracy, so you could cache the converted value and update it only once per second.

  2. Don't work with timestamps in string form in the first place. E.g. pass around a time_t value (containing seconds since the Epoch as returned by time()) instead and only convert it to a string when/if you need to print it/show it to the user/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top