Printing Timer Output in Clock Format?

Hi all,

I have a counter in my program that counts up in seconds, and can count up to several hours. I then print this total on an LCD screen, and I want to print it in a clock format: [HH:MM:SS].

My current solution works, but it doesn’t preserve 2 numbers in each slot at all times - so if it’s 64 seconds in, it prints 0:1:4, and at 1012 seconds in, it prints 0:16:52. This is readable to me, but not ideal. How can I preserve 2 numbers in each slot at all times?

At the moment, I’m doing this:

void format (unsigned long t)
{
    unsigned long h = t / 3600;
    t = t % 3600;
    int m = t / 60;
    int s = t % 60;
    lcd.setCursor(0,1);
    lcd.print(h);
    lcd.print(":");
    lcd.print(m);
    lcd.print(":");
    lcd.print(s);
} 

Thanks!

if the number is smaller than 10, print a leading 0?

2 Likes

Hi @homemaltster

There are about a million ways to do this but here is a simple one:

void format (unsigned long t)
{
    unsigned long h = t / 3600;
    t = t % 3600;
    int m = t / 60;
    int s = t % 60;
    lcd.setCursor(0,1);
    if (h<10) { lcd.print("0");}  //hours might be optional 
    lcd.print(h);
    lcd.print(":");
    if (m<10) {lcd.print("0");}
    lcd.print(m);
    lcd.print(":");
    if (s<10) {lcd.print("0");}
    lcd.print(s);
}

3 Likes

Thanks @bko and @Moors7!

3 Likes

Any reason you don’t want to use Time.format(t, "%T")?
This does the breaking down of epoch times and provides a lot more formatting options of timefstr()