How to return the result of strftime as String from a method

Hello,

I'm trying to build a method that should be return the current date and time as formatted string and for some reason the returned value is not being formatted correctly.

This is the method which pretty is similar to the example of the SimpleTime.ino, but instead of printing I'm trying to return the value as string as mentioned above:

String getCurrTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("No time available (yet)");
    time_set_flg = false;
    return "No time available (yet)";
  }
  char timeStringBuff[25];

  strftime( timeStringBuff, 
             sizeof(timeStringBuff), 
             "%Y/%m/%d %H:%M:%S %Z", 
             &timeinfo);

  // return timeStringBuff;
  // return String( timeStringBuff );

  String buffer( timeStringBuff );
  
  Serial.printf( "timeStringBuff: %s buffer: %s\n", 
                 timeStringBuff, 
                 buffer );  
  return buffer;
}

I commented out the attempt of returns from the formatted variable timeStringBuff and tried converting the result to a buffer variable to print the value, this is the output:

timeStringBuff: 2023/07/29 21:22:00 CDT buffer: �T�?

Any idea why the char buffer timeStringBuff cannot be returned or converted as String?, any help would be greatly appreciated.

Thank you

Try

Serial.printf( "timeStringBuff: %s buffer: %s\n", 
                 timeStringBuff, 
                 buffer.c_str() );

Thanks Paul, that did the trick.

As a side note (for anybody that could have this issue), I also had to use the c_str() in the variable from the caller method to present the data in the formatted way.

Yes, that's right. The "%s" in the format parameter you give to printf() tells it to expect a string not a String. A string is a pointer/reference to a C style string, which is an array of char with a null-terminator. A String is a C++ style object. Fortunately, String objects have a method which turns it into a string.

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