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() {
}
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 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.
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.