C Library for Parsing Date Time [closed]

2020-01-31 03:50发布

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

标签: c date parsing
9条回答
Bombasti
2楼-- · 2020-01-31 04:24

In Windows, there is VarDateFromStr which can automatically parse many formats if used like this:

LPCWSTR dateString = L"
DATE result;
HRESULT hr = ::VarDateFromStr(dateString,
                              LOCALE_ALL,
                              0,
                              &result);

if (FAILED(hr))
{
    /* handle error */
    /* DISP_E_TYPEMISMATCH means that it didn't recognize the format. */
}

It will generally recognize numeric formats, but can also parse "September 10 2009 12:30 AM", without Monday and on my German computer without th, but that might be locale-dependent. The words must be in the local language, for example it will need "June" on English systems but "Juni" on German systems.

查看更多
3楼-- · 2020-01-31 04:27

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;
}
查看更多
Bombasti
4楼-- · 2020-01-31 04:28

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

查看更多
贼婆χ
5楼-- · 2020-01-31 04:28

The notmuch mail project has a GPLv2+ parser for date strings. It supports absolute and relative dates in a variety of user friendly formats, although relative dates only refer to the past. The code is in the parse-time-string subdirectory of the notmuch source tree.

查看更多
萌系小妹纸
6楼-- · 2020-01-31 04:30

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

查看更多
Lonely孤独者°
7楼-- · 2020-01-31 04:36

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.

查看更多
登录 后发表回答