How to correctly check strptime for valid dates in C

I am doing the following to convert and check the date, however, I am not sure why the next date continues to check as true.

Will %d check only on [01,31] + leading zeros ? Is there a better and more accurate way to do this?

 #include <time.h> #include <stdio.h> #include <stdlib.h> int main () { struct tm tm; char buffer [80]; char *str = "29/Jan/2012"; if (strptime (str, "%Y/%b/%d", &tm) == NULL) exit(EXIT_FAILURE); if (strftime (buffer,80,"%Y-%m-%d",&tm) == 0) exit(EXIT_FAILURE); printf("%s\n", buffer); // prints 29-01-20 return 0; } 
+6
source share
1 answer

It returns non-NULL because the initial substring 29/Jan/20 matches the pattern (in particular, 20 matches the final %d in the pattern).

If strptime() returns non- NULL , it returns a pointer to the next character after the part of the input string that matches the pattern. Thus, in this case, it will return a pointer to the character '1' in the date string.

If you want to make sure that nothing is left in the input line, you need to check that the return value indicates a terminating zero at the end of the input line:

 int main () { struct tm tm; char buffer [80]; char *str = "29/Jan/2012"; char *end = strptime(str, "%Y/%b/%d ", &tm); if (end == NULL || *end != '\0') exit(EXIT_FAILURE); if (strftime (buffer,80,"%Y-%m-%d",&tm) == 0) exit(EXIT_FAILURE); printf("%s\n", buffer); // prints 29-01-20 return 0; } 

Please note that I added the trailing space to the strptime() template - this allows you to return spaces in the input file. If you do not want to allow this, use your original template.

+5
source

Source: https://habr.com/ru/post/916969/


All Articles