How to format time() from 2:23:4 to 02:23:04, add leading zeros.

I have not been able to find an example of this, is it so obvious no one asks?

So using lcd.print(second()); for example, what is the accepted method to format the result?

Like: lcd.print(second(), 00) // Incorrect

Suggestions?

Your lucky day…

if( hour() < 10 )
   lcd.print( "0" );
lcd.print( hour() );

For a more general approach that might work better when you're trying to do more complex formatting, I'd use sprintf() to format the value into a local buffer and then print that string buffer to the display device. Printf() and related functions make it easy to do this sort of thing e.g.:

char buf[10]; // must be long enough to hold the resulting string including the null terminator
sprintf(buf, "%02d:%02d:%02d", hours, mins, secs);
lcd.print(buf);

FYI, I wrote this blog post last year to explain exactly how to do that with sprintf:

Thanks

I used:

char buf[19];

sprintf(buf, "%02d:%02d:%02d -%02d/%02d/%4d", hour(), minute(), second(), month(), day(), year());
  lcd.print(buf);

Thanks for all the contributions, this has been a worthwhile lesson.

You are trying to write 20 characters into an array that can hold 19. Good luck with that.

21 including the null terminator, if I counted correctly.

21 including the null terminator, if I counted correctly.

Good thing someone can. :slight_smile: