2

I'm using the following routine to print the current time on the com port. I would like to capture this as a string so I can display it using ePaper.

void printLocalTime()
{
  time_t rawtime;
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo))
  {
    Serial.println("Failed to obtain time");
   return;
  }
 Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

produces - Saturday, May 12 2018 12:18:27

6
  • That's clever. How are you getting Serial.println to respond to that format?
    – Majenko
    May 12 '18 at 11:26
  • try CStringBuilder from StreamLib
    – Juraj
    May 12 '18 at 11:26
  • @Majenko, it is ESP32 Arduino core package
    – Juraj
    May 12 '18 at 11:27
  • Oh, so nothing to do with Arduino then. It's non-standard functionality.
    – Majenko
    May 12 '18 at 11:27
  • Personally I'd use sprintf() to place things into a char array - though you'd have to do the textual formatting (day names, etc) yourself. Or the standard C library functions may work for you (or they may not).
    – Majenko
    May 12 '18 at 11:28
6

To achieve what you want you probably want to use the "string format time" function strftime (docs). You would write the result in a character buffer, which you can also print directly without having to convert it to String object.

So, the following code should work:

void printLocalTime()
{
  time_t rawtime;
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo))
  {
    Serial.println("Failed to obtain time");
   return;
  }
  char timeStringBuff[50]; //50 chars should be enough
  strftime(timeStringBuff, sizeof(timeStringBuff), "%A, %B %d %Y %H:%M:%S", &timeinfo);
  //print like "const char*"
  Serial.println(timeStringBuff);

  //Optional: Construct String object 
  String asString(timeStringBuff);
}

The overload for Serial.print also does this exact same thing:

size_t Print::print(struct tm * timeinfo, const char * format)
{
    const char * f = format;
    if(!f){
        f = "%c";
    }
    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);
    print(buf);
    return written;
}
2
  • Perfect, except '&time_info);' should be &timeinfo);, Just what I was aiming for and missing. May 13 '18 at 19:59
  • @SimonMarkham corrected, thanks for spotting. May 13 '18 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.