If your intent is to have a real-time clock, the recommendation to use the Time & Date functions from the reference is the easiest option. If you want to display a digital clock accurate to the millisecond, the modulo and division operators are your best friends. This method for a stopwatch app I made takes in milliseconds as an input and returns a String as an output, with the String being formatted hh:mm:ss:ms
String timeFormat(int millis) {
String t = "";
int hours = millis / 3600000;
//there are 3600000 milliseconds in 1 hour, so integer division will produce the number of hours
int minutes = (millis % 3600000) / 60000;
//there are 60000 milliseconds in 1 minute, but it will not suffice to simply divide, as the number of hours needs to be disregarded when counting minutes.
//This is done through the modulo operator (%). Modulo returns the remainder of a division operation.
//Without the modulo, when the minutes pass 59, the minute will count 60, 61, etc.
//But, with the modulo, when minutes pass 59, the number of milliseconds used to calculate minutes resets to zero, which is the intended behavior of the clock.
int seconds = (millis % 60000) / 1000;
//The same logic is applied to seconds and milliseconds.
int milliseconds = millis % 1000;
//The rest is just string formatting
t += hours + ":";
if (minutes < 10) {
t += "0";
}
t += minutes + ":";
if (seconds < 10) {
t += "0";
}
t += seconds + ".";
if (milliseconds < 10) {
t += "00";
} else if (milliseconds < 100) {
t += "0";
}
t += milliseconds;
return t;
}
If you want to use this function, you’ll have to look elsewhere to find how to get a real-time millisecond count, and you may have to adjust the method to take a long
as an input instead of an integer.