Getting time in string

Line 4 outputs " Start: 08:50:51" and I have each part of the time in a string.
Now I want to take each part of the time from the local time and put into strings for comparison.

Line 9 outouts "08".
But why doesn't serial print of nowhr not give me the same result? It outputs "%H"?
How can I get the hours from timeonfo into a variable?

  String starthr = String(DATA[0][9]).substring(0,2);
  String startmin = String(DATA[0][9]).substring(3,5);
  String startsec = String(DATA[0][9]).substring(6);
  Serial.println("  Start: " + starthr + ":" + startmin + ":" + startsec);

 struct tm timeinfo;
  getLocalTime(&timeinfo);

  Serial.print(&timeinfo, "%H");  
  String nowhr = (&timeinfo, "%H");  
  String nowmin = (&timeinfo, "%M");  
  String nowsec = (&timeinfo, "%S");  

  Serial.println(nowhr);
  Serial.println("  Nu: " + nowhr + ":" + String(nowmin) + ":" + nowsec);

  if(nowhr==starthr){
    Serial.println("  Time is equal");
  }

First of all, you haven't specified what kind of Arduino: Uno? Mega? ESP8266? ESP32?
That's important because if you're on Arduino, using "String" class is usually deprecated because it can cause memory fragmentation problems, unpredictable behaviours up to complete crashes due to lack of a garbage collector. So if possible, never, ever, use "String".

I suppose DATA is a char array and DATA[0][9] contains a string (not "String", but a "C string").
Said that, if the date has the format "HH:MM:SS" you just need to create another string from timeinfo, using the same format and then directly compare those two strings using strcmp() (telling you if they are equal, or the first less than the second or viceversa).

So:

  struct tm timeinfo;
  getLocalTime(&timeinfo);
  // Convert to HH:MM:SS
  char locTime[9];
  sprintf(locTime, "%02d:%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
  Serial.print("cur="); Serial.print(DATA[0][9]); Serial.print(" loc="); Serial.println(locTime);
  // Compare
  if (strcmp(locTime,DATA[0][9]) == 0) {
    Serial.println("  Time is equal");
  }
3 Likes

Thanks, this works fine. My problem is that I do not really understand the struct tm, I think.

1 Like

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