4

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

Rohit Gupta
  • 618
  • 2
  • 5
  • 18
Simon Markham
  • 43
  • 1
  • 1
  • 3

1 Answers1

8

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;
}
Maximilian Gerhardt
  • 3,646
  • 16
  • 18