How to work with strings that are dates?

I am trying to print to the monitor data from my arduino sensors. I have the tempature and distance vaules working fine.
I am trying to display the date and time on the output. I have tried to use strcpy and strcat functions but the date or time are not Char*. I am not sure how to approach this - as an array character by character or some sort of String to Char function?
I am using NTPClient to receive network date and time.
When I try to use

strcat(buffer, timeClient.getFormattedTime());

I am getting a Char* error.

I have tried

strcat(buffer, timeClient.getHours());

I get an "invalid converstion "int" to "const char*" error

Check the .h for the NTPClient.
getFormattedTime() returns a String
so to copy to your buffer you need strcat(buffer, timeClient.getFormattedTime().c_str());
BUT strcat is a very dangerous method as it can easily overflow you buffer if you are not vary careful. The recommended alternative is strlcat( ) see strlcpy_strlcat.ino for an example sketch of how to use it and how to detect errors.

But Arduino Strings or my SafeString library are your friends here.
Both them protect against buffer overflows and let you write code like
str += timeClient.getHours(); // convert int to char.

Since you are using a char buffer[xx] you can just wrap it in a SafeString to get the buffer updated with the result
cSFA(sfBuffer,buffer); // wrap buffer in a SafeString, sfBuffer
sfBuffer.clear(); // get rid of random buffer contents
sfBuffer = timeClient.getHours(); // buffer now has \0 terminated hr as chars
sfBuffer.print(timeClient.getHours()); // all the normal print methods will print to your buffer

SafeString protects your buffer from overflows and can print error msgs when/if that happens if you include the
in setup();
See the link above for a tutorial.

1 Like

For display/print only, there is rarely any need for concatenation,
just display/print one thing after the other.

The Serial stream will concatenate the output automatically.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.