O.nunez O.nunez - 2 months ago 7
C Question

Convert a String into a Date format, anyway

i have a char with this data"20161909132409" a 14 digits string in C language, and i want to convert this to a this format "YYYY-dd-mm hh:mm:ss" and look like "2016-19-09 13:24:09", but i don't know how to do it, someone can 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 add the delimitator with the strcat function??

Answer

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.