dangom dangom - 22 days ago 7
C Question

Converting date to ISO8601 from char array

I've got a date and a time as floats.

float thedate = 20161115;
float thetime = 181011.377500;


I want to convert them to ISO8601 date-time format, in other words, write them to a file as "2016-11-15T18:10:11.377500"

I managed to get these values inside of a char array by doing the following:

char datetimestr[64];
snprintf(datetimestr, sizeof(datetimestr), "%8.0f%f", thedate, thetime);
printf(datetimestr);


And this prints: "20161115181011.377500"

I've read that functions such as
strftime
and
strptime
can parse these numbers and output them properly, but for that I guess I need some arch specific headers?

What is the recommended way to achieve what I need? Ideally in a way that runs everywhere.

Any help or further references would be greatly appreciated.

Answer

Code could print the values and then parse them again

int main() {
  long thedate = 20161115;
  float thetime = 181011.377500f;
  char buf[80];
  snprintf(buf, sizeof buf, "%+08ld%+08f", thedate, thetime);
  int y,M,d,h,m;
  float s;
  int n = 0;
  sscanf(buf, "%5d%2d%2d%3d%2d%f%n", &y, &M, &d, &h, &m, &s, &n);
  if (n) {
    // ISO 8601 specifies a sign must exist for distant years.
    printf((y >= 0 && y <= 9999) ? "%4d" : "%+4d" , y);
    printf("-%02d-%02dT%02d:%02d:%02.6f\n", M, d, h, m, s);
  }
  puts(buf);
  return 0;
}

Output

2016-11-15T18:10:11.375000