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";
}

Serial console

Serial output from the firmware.

Convert millis() to readable time serial console

References