tags:

views:

987

answers:

5

Is one aware of a date parsing function for c. I am looking for something like:

time = parse_time("9/10/2009");
printf("%d\n", time->date);
time2 = parse_time("Monday September 10th 2009")    
time2 = parse_time("Monday September 10th 2009 12:30 AM")

Thank you

+1  A: 

Unfortunately, the only thing in the standard library is getdate. It will handle many time formats, but you need to know the format in advance - not just pass a generic string to the function.

It's also not supported on Visual C++, if that's an issue for you. The Gnu C runtime supports this routine, however.

Reed Copsey
is there anything that is not in the standard and poratble?
adk
+1  A: 

The Julian Library does much of what you ask -- see in particular how its parsing works. However I don't think it quite stretches ALL the way to your requirements (that Monday, I believe, would throw it for a spin;-).

Alex Martelli
A: 

In time.h you have strptime:

// Scan values from buf string into tptr struct. On success it returns pointer
// to the character following the last character parsed. Otherwise it returns null.
char * strptime(const char* buf, const char* format, struct tm* tptr)

which does the opposite of

// Format tm into a date/time string.
size t strftime(char* s, size t n, const char* format, const struct tm* tptr)

Click here for the complete Reference on Wikipedia

blak3r
What if I do not know the format?
adk
Not in VC++ either....
Mitch Wheat
@adk hmm... well you need to give some instruction in order for it to know whether your feeding it a month versus a day or year... ya know? But, you could for a given input string try to parse it with multiple formats and keep trying it until the function doesn't return null.
blak3r
@Mitch Wheat - dunno about VC++ did you check ctime?
blak3r
+1  A: 

There are two fairly common approaches in C:

  1. Use strptime() with an array of supported formats you accept.

  2. Bang head against table a lot, and then either give up or use another language which has a usable library already (like perl or python).

James Antill
A: 

Git has a portable date parsing library, released under GPLv2. You may be able to use that. I think you want approxidate_careful().

Mark Lodato