Tuesday, October 4, 2011

How to use strptime() function in Windows

The GNU C strptime function is used to convert a given string (s), which is described as format, into a standard C time struct called tm:

char *strptime(const char *s, const char *format, struct tm *tm);


This time function is very handy when you try to convert a DateTime string into a time struct in C. And is often used together with its counterpart, strftime, to perform translation of the input DateTime string in the original format into the target format (e.g. here).


Recently, when working with the program using VS 2005 compiler, I found that the strptime function was not supported in the Windows' compiler. When checking out the time.h header file in \VC\include\time.h in the Visual Studio folders, you won't see the declaration of the strptime. So in order to use this function on Windows:


1. Since the glibc is designed for UNIX-like system, and it is advisable to use a gcc compiler on Windows (e.g. cygwin) to compile your program;


2. Or use other implementations instead:
1) http://plibc.sourceforge.net/doxygen/strptime_8c-source.html
2) http://www.opensource.apple.com/source/lukemftp/lukemftp-3/lukemftp/libukem/strptime.c
3) (In C++, Boost C++ Libs) http://www.boost.org/doc/libs/1_47_0/doc/html/date_time/date_time_io.html


3. Or write your own conversion function strptime().



2 comments:

  1. You should probably mention the Open source implementation from NetBSD as well:
    http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD

    ReplyDelete
    Replies
    1. Sorry, that is not a solution for Windows

      Delete

(Coding && Eating) || Sleeping