views:

2943

answers:

4

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  A: 

An open-source version (BSD license) of strptime() can be found here: http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD

You'll need to add the following declaration to use it:

char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict);
Adam Rosenfield
+6  A: 

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

ravenspoint
+1 for pointing out a cross-platform solution.
A: 

I ended up using the post by repostor located at on the Msdn Forums. I found it had the least amount of dependencies and issues.

Carlosfocker
+1  A: 

If you don't want to port any code or condemn your project to boost, you can do this:
1. parse the date using sscanf
2. then copy the integers into a struct tm (subtract 1 from month and 1900 from year -- months are 0-11 and years start in 1900)
3. finally, use mktime to get a UTC epoch integer

Just remember to set the isdst member of the struct tm to -1, or else you'll have daylight savings issues.

amwinter