Reputation: 181
I use strptime
to parse datetime string into tm
structure.
But I faced a problem:
I have date in this format:
Thu Dec 13 23:44:45 MSK 2012
I parse Thu Dec 13 23:44:45
with "%a %b %d %T"
format string.
But I can't understand how to parse year. I can't just use "%a %b %d %T MSK %Y"
because I want locale-independent parser.
Can I just skip MSK
word? Or any other way to solve the problem?
Upvotes: 3
Views: 2410
Reputation: 181
I didn't find an answer, so I wrote my own datetime parser:
time_t timeParse(const char *string, struct tm *datetime)
{
char dn[4], mn[4], ln[4];
int d, h, m, s, y;
sscanf(string, "%s %s %d %d:%d:%d %s %d", dn, mn, &d, &h, &m, &s, ln, &y);
datetime->tm_sec = s;
datetime->tm_min = m;
datetime->tm_hour = h;
datetime->tm_mday = d;
if (!strcmp(mn, "Jan")) datetime->tm_mon = 0;
if (!strcmp(mn, "Feb")) datetime->tm_mon = 1;
if (!strcmp(mn, "Mar")) datetime->tm_mon = 2;
if (!strcmp(mn, "Apr")) datetime->tm_mon = 3;
if (!strcmp(mn, "May")) datetime->tm_mon = 4;
if (!strcmp(mn, "Jun")) datetime->tm_mon = 5;
if (!strcmp(mn, "Jul")) datetime->tm_mon = 6;
if (!strcmp(mn, "Aug")) datetime->tm_mon = 7;
if (!strcmp(mn, "Sep")) datetime->tm_mon = 8;
if (!strcmp(mn, "Oct")) datetime->tm_mon = 9;
if (!strcmp(mn, "Nov")) datetime->tm_mon = 10;
if (!strcmp(mn, "Dec")) datetime->tm_mon = 11;
datetime->tm_year = y - 1900;
return mktime(datetime);
}
I fill necessary tm structure
fields manually and mktime
fills remaining fields: tm_wday
, tm_yday
, tm_isdst
.
You should call it this way:
time_t t = timeParse("Thu Dec 13 23:44:45 MSK 2012", &datetime);
Upvotes: 3