# JS Tip of the Day: Format Time Strings with Padding

**URL:** <https://forum.kirupa.com/t/js-tip-of-the-day-format-time-strings-with-padding/643145>\
**Category:** web dev\
**Created:** [March 22, 2020, 12:55pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-format-time-strings-with-padding/643145 "2020-03-22T12:55:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [March 22, 2020, 12:55pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-format-time-strings-with-padding/643145/1 "2020-03-22T12:55:52Z")

</div>

**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.

```javascript
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()`.

```javascript
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');
    console.log(`${secStr}:${msStr}`);
}

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:

- [padStart on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)
- [padEnd on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd)
