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

argon
Tags: #<Tag:0x00007f03933e82b0>

#1

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


#2

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


#3

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.