Better RTC Time String

This is my slightly updated version (from the example) of the RTC string generator. The original version generates odd times like 12:2:9 instead of 12:02:09, this fixes that:

void clockUpdate()
{
  if(minute() < 10 && second() < 10)
  {
    currentTime = String(hour()) + ":0" + minute() + ":0" + second();
  }
  else if(minute() < 10)
  {
    currentTime = String(hour()) + ":0" + minute() + ":" + second();
  }
  else if(second() < 10)
  {
    currentTime = String(hour()) + ":" + minute() + ":0" + second();
  }
  else
  {
    currentTime = String(hour()) + ":" + minute() + ":" + second();
  }
  currentDate = String(month()) + "/" + day();
}

Super simple fix, but one that I had to make from the example

Nice… I had something similar here, but then @Costas showed me an even simpler method

char currentTime[9];
char currentDate[11];

void clockDisplay() {
sprintf(currentTime, "%02d:%02d:%02d", hour(), minute(), second());
sprintf(currentDate, "%02d/%02d/%04d", month(), day(), year());
Blynk.virtualWrite(V12, currentTime);  // Send time to Display Widget
Blynk.virtualWrite(V13, currentDate);  // Send date to Display Widget
}

However it did take me a bit to get my head around it… compared to our more basic if-else methods.

2 Likes