How to change format of a date?

Hello

I have a string of format: 20170729112303.000

How can I change this to a string or char-array of format: 2017-07-29T11:23:03.000 ?

1 Like

I have a string of format: 20170729112303.000

Is it a string or a String ?

1 Like

Because you know the input and output format, and the offsets are fixed, you can just move the characters around using memcpy/memmove:

void setup() {
  Serial.begin(115200);
  while (!Serial);
  char str[24] = "20170729112303.000"; // "2017-07-29T11:23:03.000" is 23 characters + terminating NULL
  Serial.println(str);
  memmove(&str[17], &str[12], 7); // seconds  (dest and source overlap, so use memmove instead of memcpy)
  str[16] = ':';
  memcpy(&str[14], &str[10], 2); // minutes
  str[13] = ':';
  memcpy(&str[11], &str[8], 2); // hour
  str[10] = 'T';
  memcpy(&str[8], &str[6], 2); // day
  str[7] = '-';
  memcpy(&str[5], &str[4], 2); // month
  str[4] = '-';
  Serial.println(str);
  Serial.println("2017-07-29T11:23:03.000");
  Serial.print(strcmp(str, "2017-07-29T11:23:03.000") ? "doesn't match" : "matches");
}

void loop() {}

Pieter

1 Like

PieterP - Sorry for the late reply but... THANKS! Worked perfectly :slight_smile: