Convert a string to a date in C++

#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);

I figured it out without using strptime.

Break the date down into its components i.e. day, month, year, then:

struct tm  tm;
time_t rawtime;
time ( &rawtime );
tm = *localtime ( &rawtime );
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
mktime(&tm);

tm can now be converted to a time_t and be manipulated.


For everybody who is looking for strptime() for Windows, it requires the source of the function itself to work. The latest NetBSD code does not port to Windows easily, unfortunately.

I myself have used the implementation here (strptime.h and strptime.c).

Another helpful piece of code can be found here. This comes originally from Google Codesearch, which does not exist anymore.

Hope this saves a lot of searching, as it took me quite a while to find this (and most often ended up at this question).