I am trying to use strptime(buf, &pattern,&result) to convert char[] containing date into tm structure.
I am using function like this:
if(strptime(buf, &pattern,&result) == NULL)
{
printf("\nstrptime failed\n");
...
and everything works if my variables are defined like this:
char buf[] = "26/10/2011";
char pattern[] = "%d/%m/%y";
struct tm result;
but if I change them into:
char buf[] = "2011/26/10";
char pattern[] = "%y/%d/%m";
struct tm result;
I get "strptime failed". Notice, that I have only put year in the beginning (both in buf and pattern).
Help appreciated. My final target is to convert string in this format: 2011-10-26T08:39:21
It's because the lower case
%yis for the two-digit year within the century. Try changing it to uppercase%Yand it will work okay. You can see this from the following program:This outputs
2020, meaning that the year is being read as just the20portion of2011, with the remainder being ignored. If you use upper-case%Y, it outputs the correct2011instead.Code that generates the conversion error using the reversed format:
will work fine (ie, output
2011) when you change thepatternvalue to"%Y/%m/%d".