C : Validation in strptime

Andy Stow Away picture Andy Stow Away · Jul 11, 2012 · Viewed 9.5k times · Source

strptime() function in C fails to detect invalid dates. Ex: 2011-02-31 , 2011-04-31. Is there any other function or workaround to this problem

Answer

jxh picture jxh · Jul 11, 2012

You can use mktime to normalize your structure after using strptime.

struct tm ltm = {0};
char buf[] = "2011-02-31";
puts(buf);
strptime(buf, "%Y-%m-%d", &ltm);
mktime(&ltm);
strftime(buf, sizeof(buf), "%Y-%m-%d", &ltm);
puts(buf);

The example above will produce the output below:

2011-02-31
2011-03-03

If the strings before and after mktime do not match, then you know the input string was not a valid date.

If you need to know which field was invalid, you can save a copy of the ltm structure before calling mktime. Then, you can examine if the day (tm_mday), month (tm_mon), or year (tm_year) was the one in the invalid format. For tm_mon, 0 is January, and 11 is December. For tm_year, it is the number of years since 1900. Remember to account for leap year when validating the day of the month for February.