O.nunez - 1 month ago 3x
C Question

# Convert a string into a specific date format

I have a 14 digit string with this data

`20161909132409`
, and I want to convert it to this format
`YYYY-dd-mm hh:mm:ss`
so it looks like:
`2016-19-09 13:24:09`
, but I don't know how to do it, can someone help me with the code please?

``````  char * strA = "00000000000000", * strB = "-", strC[50];
int x = 4;
strncpy(strC,strA,x);
strC[x]= '\0';
strcat(strC,strB);
strcat(strC,strA+x);
printf("%s\n",strC);
return 0;
``````

Can someone give an idea of how to add the deliminator with the strcat function?

The is one of those scenarios, where a brute force approach of simply walking a pointer down the original datestring to insert the required date and time format separators, is just as easy, and efficient as anything else. The following code simply builds a buffer from your original string, inserting the the formatting in buffer at the appropriate separators and the required points as the data is copied from `data` to `buf` the index in `buf` is simply derived from the position of pointer `p`. At the end, after all separators have been inserted and all characters copied to `buf`, `buf` is `nul-terminated` and is no in a form to pass to your date functions., e.g.

``````#include <stdio.h>

int main (void) {

char data[] = "20161909132409",
buf[32] = "", *p = buf;
size_t i = 0;

for (; data[i]; i++) {
if (i < 4) *p++ = data[i];
else if (i == 4) { *p++ = '-'; *p++ = data[i]; }
else if (i < 6) *p++ = data[i];
else if (i == 6) { *p++ = '-'; *p++ = data[i]; }
else if (i < 8) *p++ = data[i];
else if (i == 8) { *p++ = ' '; *p++ = data[i]; }
else if (i < 10) *p++ = data[i];
else if (i == 10) { *p++ = ':'; *p++ = data[i]; }
else if (i < 12) *p++ = data[i];
else if (i == 12) { *p++ = ':'; *p++ = data[i]; }
else if (i < 14) *p++ = data[i];
}
*p = 0; /* nul-terminate */

printf (" original  : '%s'\n formatted : '%s'\n", data, buf);

return 0;
}
``````

Example Use/Output

``````\$ ./bin/fmrdatestr
original  : '20161909132409'
formatted : '2016-19-09 13:24:09'
``````

Look it over and let me know if you have any questions.

Source (Stackoverflow)