Parse date and time represented in custom string in C
The C library function strptime() can be used to convert date and time represented in custom string format to a broken-down representation in struct tm. Here is the declaration of strptime() function.
char *strptime(const char *s, const char *format, struct tm *tm);
The following example parses a date and time string “2008-12-31 21:45:10” and converts first in to broken-down time format struct tm. Then converts it back to string format in another representation.
[neo@techpulp ~]# cat parse_time.c
#include <stdio.h>
#include <time.h>
char *times[] = {
"2008-12-31 21:45:10",
NULL
};
int main(int argc, char *argv[])
{
struct tm tm;
char buf[255];
strptime("2008-12-31 21:45:10", "%Y-%m-%d %H:%M:%S", &tm);
strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
puts(buf);
return 0;
}
[neo@techpulp ~]#
Let us compile and execute the above C program.
[neo@techpulp ~]# gcc parse_time.c -o parse_time [neo@techpulp ~]# ./parse_time 31 Dec 2008 21:45 [neo@techpulp ~]#

