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
6122 gold badges5 silver badges18 bronze badges
asked May 12, 2018 at 11:20
6
  • That's clever. How are you getting Serial.println to respond to that format? Commented May 12, 2018 at 11:26
  • try CStringBuilder from StreamLib Commented May 12, 2018 at 11:26
  • @Majenko, it is ESP32 Arduino core package Commented May 12, 2018 at 11:27
  • Oh, so nothing to do with Arduino then. It's non-standard functionality. Commented May 12, 2018 at 11:27
  • 1
    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). Commented May 12, 2018 at 11:28

1 Answer 1

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;
}
answered May 12, 2018 at 11:30
1
  • Perfect, except '&time_info);' should be &timeinfo);, Just what I was aiming for and missing. Commented May 13, 2018 at 19:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.