2016-05-05 4 views
1

良い日、時間のHTMLのJS

私はHTMLコードで次の時間関数JSを使用しています。私はまだJSを学んで理解していて、それを試しています。しかし、私は最近、分が10未満のときは14:05ではなく、14:5など、0が取り除かれていることに気付きました。これを修正するためのクイックフォーマットの方法はありますか?

おかげで、事前に、ここでは私の知る限りではJS機能

function updateClock() { 
    var now = new Date(), 
     months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; 
     time = now.getHours() + ':' + now.getMinutes(); 

     date = [now.getDate(), 
       months[now.getMonth()], 
       now.getFullYear()].join(' '); 

    // set the content of the element with the ID time to the formatted string 
    // document.getElementById('time').innerHTML = [date, time].join(' '); 
    document.getElementById('time').innerHTML = ["Today is", date, "and the time is", time].join(' '); 

    setTimeout(updateClock, 1000); 
} 
updateClock(); 

答えて

1

あなたの分の値が10未満であるかどうかを確認し、それの前に0を追加することができるはずです。

// If the minutes are greater than 10, pad them with a '0' 
time = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes(); 

あなたはsee a working example hereとは立証することができます以下:

enter image description here

+0

私は本当にこのような、それのためのマクロのこの種を使用するのではと思ったことはありません。私はそれをテストするために少し待つ必要があり、Windows 10は実際に私が私の喜びで時間を変更することを許可していないので、それが動作することを確認してください。 – ricknaght

+0

疑問のように、これは私のスペクトルを大きく広げてくれて、ありがとう。 – ricknaght

0

だ、このための組み込みの方法はありません。ただし、必要に応じて3進演算子を使用して0を追加することもできます。

var mins = now.getMinutes(); 
    var minsFixed = mins < 10 ? '0' : '' + mins; 
    time = now.getHours() + ':' + minsFixed; 
0

ただ、このように1つの以上のフォーマット機能を使用して、どこでもそれを呼び出す:

function zero(num) { 
    return num < 10 ? '0' + num : num; 
}