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

Hi,
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.begin(9600);

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

void loop() {
}

The output is something like this…
05:26AM
PW╗

What am I missing?
thanks
Pete

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 Time.now() 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

Thanks! This formatted my time correctly!

Before this, I kept getting single digits when the Minutes were less than 2 digit numbers.

It would show 1 : 1 PM instead of 1 : 01 PM.

Found this which shows how to use your code to format the time anyway you desire.

http://www.cplusplus.com/reference/ctime/strftime/

1 Like