strptime() equivalent on Windows?

Viewed 61003

Is there a good equivalent implementation of strptime() available for Windows? Unfortunately, this POSIX function does not appear to be available.

Open Group description of strptime - summary: it converts a text string such as "MM-DD-YYYY HH:MM:SS" into a tm struct, the opposite of strftime().

7 Answers

This does the job:

#include "stdafx.h"
#include "boost/date_time/posix_time/posix_time.hpp"
using namespace boost::posix_time;

int _tmain(int argc, _TCHAR* argv[])
{
    std::string ts("2002-01-20 23:59:59.000");
    ptime t(time_from_string(ts));
    tm pt_tm = to_tm( t );

Notice, however, that the input string is YYYY-MM-DD

This is a copy-and-paste-capable C example of the answer @amwinter posted, although I did not use sscanf() - the *scanf() family of functions is IMO too perverse to do robust parsing with:

(headers and error checking omitted to keep the example short enough to prevent a vertical scroll bar from getting created)

    // format will be YYYYmmddHHMMSSZ
    const char *notAfter = getNotAfterStringFromX509Cert( x509 );
    struct tm notAfterTm = { 0 };

#ifdef _WIN32
    char buffer[ 8 ];

    memset( buffer, 0, sizeof( buffer ) );
    strncpy( buffer, notAfter, 4 );
    notAfterTm.tm_year = strtol( buffer, NULL, 10 ) - 1900;

    memset( buffer, 0, sizeof( buffer ) );
    strncpy( buffer, notAfter + 4, 2 );
    notAfterTm.tm_mon = strtol( buffer, NULL, 10 ) - 1;

    memset( buffer, 0, sizeof( buffer ) );
    strncpy( buffer, notAfter + 6, 2 );
    notAfterTm.tm_mday = strtol( buffer, NULL, 10 );

    memset( buffer, 0, sizeof( buffer ) );
    strncpy( buffer, notAfter + 8, 2 );
    notAfterTm.tm_hour = strtol( buffer, NULL, 10 );

    memset( buffer, 0, sizeof( buffer ) );
    strncpy( buffer, notAfter + 10, 2 );
    notAfterTm.tm_min = strtol( buffer, NULL, 10 );

    memset( buffer, 0, sizeof( buffer ) );
    strncpy( buffer, notAfter + 12, 2 );
    notAfterTm.tm_sec = strtol( buffer, NULL, 10 );

    time_t result = mktime( &notAfterTm );

This is a really simple case, where the input string is in a format known exactly, so it's extremely easy to parse.

There is a version of strptime() for windows available at https://github.com/p-j-miller/date-time . The same location includes a matching strftime() function and a comprehensive test program. This also works under Linux if you need to create code that works on both OS's.

Related