C : Validation in strptime

◇◆丶佛笑我妖孽 提交于 2019-12-30 09:51:54

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/11428014/c-validation-in-strptime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!