Using char strings and sprintf - problem with Time.format()

I’m trying to put a formatted timestamp into a string to send to Blynk. The Time.format() command works fine when I use it directly in a serial print, but not if I try to use sprintf to put it into a char string first…I get 3 strange characters, that vary with the timestamp

eg (sorry I’m not sure how to format this as a code window in the post)

char timeonlyInChar[15]; 

void setup() {

    Serial.println(Time.format(,"%I:%M%p"));                  // This will print OK
    sprintf(timeonlyInChar, "%s", Time.format(,"%I:%M%p"));   // This wont

void loop() {

The output is something like this…

What am I missing?

Time.format() returns a String object but sprintf() only knows pure C strings (aka char arrays).
So you need to cast the String object to (const char*) (or use someString.c_str() instead).

Like this

    sprintf(timeonlyInChar, "%s", (const char*)Time.format("%I:%M%p"));   // This should work

(also no need to state in Time.format() - without that parameter now is assumed)

You can use this image for preformatted text (including code blocks) or use ```cpp (as separate line without blanks) before the code block and the same without the “cpp” part after it.

For more tips and tricks you can look here

Thanks for the help ScruffR, that now makes sense. If only I had more carefully read the description for timeStr(), rather than just format(), in the Reference…it does say “Returns: String”

And thanks for the link to the Tips & Tricks, I’ll take a look.

1 Like