In this article, we are going to discuss about Formatting Time Using the Date Object and String Padding. So we will see to format the time with the help of Date object, and we are going to use milliseconds, with which we can get time in the format of (0000:00:00.00)[hhhh:mm:ss.ms]. Here we are using milliseconds to get time because we can divide milliseconds with 1000 to get seconds and with seconds we can easily get minutes and hours with little math.
So what we are aiming to get the time and put in the time format with the help of string padding.
Formatting Time Using The Date Object and String Padding
Okay, now let’s jump into the code, here we have created a function named formattedTime(m) with parameter ‘m’. In here we have declared some variables to store time, hours, minutes, seconds, milliseconds. Then we have created an object for Date(), and we have used setTime() method on it which takes milliseconds as parameter.
Now we have divided millisecond with, 3600000 to get hours, This expression we added in Math.floor(), so that we can get hours without decimals (for example, Math.floor(2.5977643)= 2). And we have converted this number to string using toString() and finally we used padStart() method to turn this hour in formatted time hour (for example, padStart(4,”0″) = 0000, padStart(2,”2″) = 22). padStart() method will create a number of string and a string to replace with, like here we have padStart(4, “0”) which will form 4 strings, and blank strings will be replaced with 0s.
Now, to get minutes, we will use formatTime.getMinutes()
method, and we will just convert to string and here we need 2 string, so we used padStart(2,"0"
). For seconds, we will do the same things as minutes, but here we will use formatTime.getSeconds()
.
Then for milliseconds, we will use formatTime.getMilliSeconds()
to get milliseconds, but we just need milliseconds in 2 digits, for that, we will divide this with 10, and we have to put this expression in Math.round() method to get round of values. (For example, Math.round(formatTime.getMilliseconds(2863)/10) will return 29 milliseconds). And then we just convert into string then again we applied padStart(2,"0")
to get result in 2 string.
Lastly, we added time in the targeted format in hms variable and we are just returning it.
let formattedTime = function(m){
let hms= "",
formatTime = new Date(),
hours = "0",
minutes = "0",
seconds = "0",
milli ="0";
formatTime.setTime(m);
hours = Math.floor(m / 3600000).toString().padStart(4,"0");
minutes = formatTime.getMinutes().toString().padStart(2,"0");
seconds = formatTime.getSeconds().toString().padStart(2,"0");
milli = Math.round(formatTime.getMilliseconds()/ 10).toString().padStart(2,"0");
hms = `${hours}:${minutes}:${seconds}.${milli}`;
return hms;
}