Convert millis() to readable time

millis time hours seconds minutes days arduino

This example contains a simple sketch to convert millis() to readable time format in days, hours, minutes and seconds. And then it prints out the time lapsed after the last print of the time.

Code

Download code
void setup() {
  Serial.begin(9600);
  while (!Serial) { }
  Serial.println("Begin conversion from millis to readable time");
}

void loop() {
  String readableTime;
  getReadableTime(readableTime);

  Serial.println(readableTime);
  delay(5000);
}

void getReadableTime(String &readableTime) {
  unsigned long currentMillis;
  unsigned long seconds;
  unsigned long minutes;
  unsigned long hours;
  unsigned long days;

  currentMillis = millis();
  seconds = currentMillis / 1000;
  minutes = seconds / 60;
  hours = minutes / 60;
  days = hours / 24;
  currentMillis %= 1000;
  seconds %= 60;
  minutes %= 60;
  hours %= 24;

  if (days > 0) {
    readableTime = String(days) + " ";
  }

  if (hours > 0) {
    readableTime += String(hours) + ":";
  }

  if (minutes < 10) {
    readableTime += "0";
  }
  readableTime += String(minutes) + ":";

  if (seconds < 10) {
    readableTime += "0";
  }
  readableTime += String(seconds) + " ago";
}

Makefile

BOARD?=esp32:esp32:t-beam
PORT?=/dev/cu.SLAB_USBtoUART

.PHONY: default lint all flash clean

default: all flash clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright *.ino

all:
	arduino-cli compile --fqbn $(BOARD) ./

flash:
	arduino-cli upload -p $(PORT) --fqbn $(BOARD)

clean:
	rm -r build

Serial console

Serial output from the firmware.

Convert millis() to readable time serial console

References