0

I would like to get it to display 0 infront of the output if it's under 10.

const time = new Date();
let hour = today.getHours();
let minute = today.getMinutes();
let second = today.getSeconds();
if (second < 10) {
  second = 0 + second;
}

console.log(`Time is ${hour} : ${minute} : ${second}`);

Instead of showing for example 19:5:7, I would like to see 19:05:07

/// Ok, I found out what the problem was. 0 was a number not a string. Just started with JS.
Thanks for the help!

Halund
  • 11
  • 3

1 Answers1

2

You could pad the value with leading zeroes.

const pad2 = s => s.toString().padStart(2, '0');

let today = new Date;
let hour = pad2(today.getHours());
let minute = pad2(today.getMinutes());
let second = pad2(today.getSeconds());

console.log(`Time is ${hour}:${minute}:${second}`);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392