[英]The “0” minute is not appearing in current time (JavaScript/HTML)
一般而言,我對編碼還很陌生,所以如果我聽起來很愚蠢,請提前道歉!
我目前正在從事有關智能鏡的項目。 GUI顯示用戶的日歷,當前時間和日期等。但是,我在構建的當前時間方面遇到問題。 出於某種原因,如果分鍾為“ 0”(例如“ 18:05”),則當前時間將不帶分鍾,例如“ 18:5”。 任何幫助將不勝感激! 這是下面的代碼;
function updateClock() { var now = new Date(), months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; time = now.getHours() + ':' + now.getMinutes(), now.getSeconds(); date = [now.getDate(), months[now.getMonth()], now.getFullYear() ].join(" "); document.getElementById("time").innerHTML = [date, time].join(" / "); setTimeout(updateClock, 1000); } updateClock();
<span id="time"></span>
提前致謝
如果分鍾小於10,則添加“ 0”
還要將now.getMinutes()保存到一個變量中,這樣就不會多次生成(浪費函數調用)。
function updateClock() { var now = new Date(); var mins = 5;//set to now.getMinutes() mins = mins < 10 ? "0"+mins : mins; var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; time =now.getHours() + ':' + mins, now.getSeconds(); date = [now.getDate(), months[now.getMonth()], now.getFullYear()].join(" "); document.getElementById("time").innerHTML = [date, time].join(" / "); setTimeout(updateClock, 1000); } updateClock();
<div id="time"></div>
('0'+now.getMinutes()).slice(-2)
這將在前面加上零,並取最后2位數字。 因此5
變為05
,最終結果為05
。 15
變成015
所以最終結果變成15
time =now.getHours() + ':' + ('0'+now.getMinutes()).slice(-2)+':'+ ('0'+now.getSeconds()).slice(-2);
您可以根據瀏覽器支持使用Intl API 。
function updateClock(element) { const now = new Date(); const date = new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'long', day: 'numeric', }).format(now); const time = new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', }).format(now); element.textContent = `${date} / ${time}`; } setInterval(updateClock.bind(null, document.getElementById('time')), 1000);
<span id="time"></span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.