C Library for Parsing Date Time

15,559

Solution 1

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;-).

Solution 2

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).

Solution 3

If the format is consistent you can use scanf family functions

#include<stdio.h>

int main()
{
    char *data = "Tue, 13 Dec 2011 16:08:21 GMT";
    int h, m, s, d, Y;
    char M[4];
    sscanf(data, "%*[a-zA-Z,] %d %s %d %d:%d%:%d", &d, M, &Y, &h, &m, &s);
    return 0;
}

Solution 4

Unfortunately, the only thing in the standard library is getdate(), defined by POSIX, not the C standard. 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.

Solution 5

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

Share:
15,559
adk
Author by

adk

Updated on July 09, 2022

Comments

  • adk
    adk almost 2 years

    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

  • adk
    adk over 14 years
    is there anything that is not in the standard and poratble?
  • adk
    adk over 14 years
    What if I do not know the format?
  • blak3r
    blak3r over 14 years
    @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
    blak3r over 14 years
    @Mitch Wheat - dunno about VC++ did you check ctime?
  • djhaskin987
    djhaskin987 over 8 years
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
  • Jani
    Jani over 8 years
    @djhaskin987 Improved the answer slightly, but there isn't much more essential information that could be added beyond pointing at the definitive source of the code. How is this possibly worse than the two upvoted answers pointing at git's date parser?