Using sprintf to publish the Time and Date

Could someone tell what I’m doing wrong using the sprinf to print a time/date char[].
I have a char[] as :

char TimeDate[19];

I then save Time and Date in the char[] TimeDate like:

TimeDate[19]=sprintf(timeBuffer, "%2d:%02d:%02d\%02d/%02d/%4d", Time.hour(), Time.minute(), Time.second(), Time.month(), Time.day(), Time.year());

I then want to display it so I use the char[] content to format it and then publish it like:

char content[128];         
sprintf(content, "%s", TimeDate[19]);
Particle.publish("Test", content, PRIVATE);

It publishes as 2 char: “18” so I’m not getting the time and date as expected

Thanks for your help

There are multiple issues with your code

  • sprintf() dose not return a string or character (which TimeDate[19] would expect), it returns the number of characters rendered in the buffer
  • you don’t assign a strings via the = sign
  • in your sprintf(content, "%s", TimeDate[19]) you are stating that you will provide a string (aka pointer to a char array) but then you only provide a single character (the one with index 19 in the array - which isn’t even allowed in a char[19], only 0…18 are valid indexes)
  • your array is too short, it doesn’t provide the space for the zero terminator ('\0')
  • the backslash in your format string needs escaping

This is how I’d do it

  Particle.publish("Test", Time.format("%T\\%m/%d/%Y"), PRIVATE);

(although this will also have the hour with a leading zero - unlike your version)

But if you are actually interested in having the formatted DateTime in a char array and insist in not having the leading zero with the hour, then this would be the way I’d go

  char TimeDate[20];
  int now = Time.now(); // take snapshot of current time to prevent inconsistencies between multiple Time.xxx() calls
  snprintf(TimeDate, sizeof(TimeDate), "%2d:%s", Time.hour(now), (const char*)Time.format(now, "%M:%S\\%m/%d/%Y"));  
  Particle.publish("Test", TimeDate, PRIVATE);

Here you find the reasoning behind the format string in Time.format()
http://www.cplusplus.com/reference/ctime/strftime

2 Likes

Thanks I’ll give that a shot.