Best way to convert time to string (int to char array)

#1

Hi,

I’m new here, been going well so far following tutorials and and forum posts/answers, but I’m stuck on a problem around converting an int to a char array to print the localtime to an ili9341 driven display.

I’ve got the following solution working to print the localtime to the display:

  static bool s_tick_tock = false;
  time_t now = time(0);
  struct tm *timeinfo = localtime(&now);

  char buf[BUFSIZ];
  int value = timeinfo->tm_hour;
  sprintf(buf, "%d", value);

  mgos_ili9341_set_font(&FreeSansBold12pt7b);
  mgos_ili9341_print(10, 10, buf);

While this works, it seems like a really inefficient way to do this, as I plan to do a fair bit on manipulation of the date time.
I’ve tried multiple solutions I found online for general C/C++ but none seem to work for me.

Any suggestions on what I could do?
Thanks.

#2

What about strftime?

1 Like
#3

Thanks for the suggestion nliviu, but it seems strftime only replaces the sprintf function and still requires extra buffers.

I guess I was really hoping maybe for something I could use inline like:

mgos_ili9341_print(10, 10, to_string(timeinfo->tm_hour).c_str());
#4

Actually, strftime is much better than what I had, which didn’t work too well and would have required a bunch of annoying logic to work properly:

static bool s_tick_tock = false;
time_t now = time(0);
struct tm *timeinfo = localtime(&now);

char time[BUFSIZ];
char hours[BUFSIZ];
char minutes[BUFSIZ];
char seconds[BUFSIZ];

sprintf(hours, "%d", timeinfo->tm_hour);
sprintf(minutes, "%d", timeinfo->tm_min);
sprintf(seconds, "%d", timeinfo->tm_sec);

sprintf(time, hours);
sprintf(time + strlen(time), ":");
sprintf(time + strlen(time), minutes);
sprintf(time + strlen(time), ":");
sprintf(time + strlen(time), seconds);

mgos_ili9341_set_font(&FreeSansBold24pt7b);
mgos_ili9341_set_fgcolor(0xff, 0xff, 0xff);
mgos_ili9341_print(40, 5, time);

to

static bool s_tick_tock = false;
time_t now = time(0);
struct tm *timeinfo = localtime(&now);

char time[BUFSIZ];
strftime(time, 80, "%I:%M:%S%p", timeinfo);

mgos_ili9341_set_font(&FreeSansBold18pt7b);
mgos_ili9341_set_fgcolor(0xff, 0xff, 0xff);
mgos_ili9341_print(25, 5, time);

Thanks again nliviu