JS Tip of the Day: Format Time Strings with Padding

Format Time Strings with Padding
Version: ES2017
Level: Intermediate

Strings have two builtin methods that allow you to add padding: padStart() and padEnd(). These create new strings that pad the original string with another string, either added to the start or end, repeating it until the resulting string matches a specified length.

let str = 'str';
console.log(str.padStart(6, '*')); // ***str
console.log(str.padEnd(6, '*')); // str***

padStart() is especially convenient for adding preceding 0’s to time values. If you want to show a seconds value in a digital display, for example, you may want to be sure that values less than 10 always have a 0 in front of it. So if you have a 3, it should be displayed as ‘03’ and not ‘3’. The following example does just that, using padStart() to add preceding 0’s to both a seconds value and a milliseconds value when displaying (logging) the time taken to run a call to setTimeout().

function logTimeTaken (startTime) {
    let timeTaken = Date.now() - startTime;
    let ms = timeTaken % 1000;
    let sec = Math.floor(timeTaken / 1000) % 60;
    let msStr = String(ms).padStart(3, '0');
    let secStr = String(sec).padStart(2, '0');

setTimeout(logTimeTaken, 1, Date.now()); // 00:001
setTimeout(logTimeTaken, 30, Date.now()); // 00:030
setTimeout(logTimeTaken, 2500, Date.now()); // 02:500
// Note: variations in setTimeout accuracy may
// show slightly different results

Because seconds values will always be shown with 2 digits (00-59), padStart() is called with a length value of 2 while milliseconds with 3 digits (000-999) uses a length of 3. This ensures each result is displayed in the format ##:### no matter how large (err, small) the actual time values are.

More info: