2016-12-12 41 views
-1
document.getElementById("time").innerHTML = formatAMPM(); 

function formatAMPM() { 
    var d = new Date(), 
    minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() : d.getMinutes(), 
    hours = d.getHours().toString().length == 1 ? '0' + d.getHours() : d.getHours(), 
    ampm = d.getHours() >= 12 ? 'pm' : 'am', 
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 
    days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 
    return days[d.getDay()] + ' - ' + months[d.getMonth()] + '. ' + d.getDate() + '. ' + d.getFullYear() + ' - ' + hours + ':' + minutes + ampm; 
} 

有人可以幫忙,讓它每分鐘更新一次嗎?如何使用Javascript更新時間

+0

使用,'的setInterval(函數,延遲)' – nmnsud

+0

https://開頭開發商。 mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval – Manwal

+0

裏面的函數格式AMPM – Sam

回答

0

使用下面的代碼setInterval

setInterval(function() { 
 
    document.getElementById("time").innerHTML = formatAMPM(); 
 
}, 1000); 
 

 
    function formatAMPM() { 
 
     var d = new Date(), 
 
      seconds = d.getSeconds().toString().length == 1 ? '0' + d.getSeconds() : d.getSeconds(), 
 
      minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() : d.getMinutes(), 
 
      hours = d.getHours().toString().length == 1 ? '0' + d.getHours() : d.getHours(), 
 
      ampm = d.getHours() >= 12 ? 'pm' : 'am', 
 
      months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 
 
      days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 
 
     return days[d.getDay()] + ' - ' + months[d.getMonth()] + '. ' + d.getDate() + '. ' + d.getFullYear() + ' - ' + hours + ':' + minutes + ':' + seconds + ampm; 
 
     }
<div id="time"></div>

0

稱爲setInterval()的函數用於定期運行某些代碼。

第一個參數是函數名,第二個參數是以毫秒爲單位的時間間隔。

例如,更換此:

document.getElementById("time").innerHTML = formatAMPM(); 

有了這個:

setInterval(function() { 
    document.getElementById("time").innerHTML = formatAMPM(); 
}, 60 * 1000); 

其中60 * 1000是在毫秒一分鐘。

+0

如果這有幫助,你可以點擊我帖子上的複選標記按鈕來接受它作爲答案。謝謝! @Sam – K48

0

像以下:

setInterval(function(){ 
    document.getElementById("time").innerHTML = formatAMPM(); 
}, 60000); // 60000 miliseconds 
相關問題