0

I have a clock made that displays the current time in Hours:Minutes:Seconds. Currently the time is displayed as so 20:30:25, but my problem is that when the time is a single digit for example 1.05 (3 seconds) am, it will appear like this on the clock 1:5:3. I want it to appear like this 01:05:03.

How can this be done?

var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes(); 
var seconds = today.getSeconds();
today = hours+':'+minutes+':'+seconds;
document.write(today);
j08691
  • 190,436
  • 28
  • 232
  • 252
user3594463
  • 113
  • 1
  • 3
  • 12

2 Answers2

5

A simple way is to use a slice(-2) trick to always let the number with a preceding zero (if needed)

Slice, with a negative parameter, takes the last n characters of a string, in this case, always a two digit value:

var today = new Date();
var hours = ("00" + today.getHours()).slice(-2);
var minutes = ("00" + today.getMinutes()).slice(-2); 
var seconds = ("00" + today.getSeconds()).slice(-2);

alert(hours+":"+minutes+":"+seconds);
LcSalazar
  • 15,390
  • 3
  • 29
  • 62
1

Simply add zeros! I used ternary operator to do it.

    var today = new Date();
    var hours = today.getHours() <10 ? "0"+today.getHours(): today.getHours();
    var minutes = today.getMinutes() <10 ? "0"+today.getMinutes(): today.getMinutes(); 
    var seconds = today.getSeconds() <10 ? "0"+today.getSeconds(): today.getSeconds();
    today = hours+':'+minutes+':'+seconds;
    document.write(today);
nicael
  • 16,503
  • 12
  • 50
  • 80