2015-07-13 23 views
4

我有這個javascript代碼應該顯示時間。有用。我不能夠增加額外的時間。可以說我想加1小時。Javascript若要添加小時數

 <script type="text/javascript"> 
     Date.prototype.addHours = function(h) {  
      this.setTime(this.getTime() + (h*60*60*1000)); 
      return this; 
     } 
     // This function gets the current time and injects it into the DOM 

     function updateClock() { 
      // Gets the current time 
      var now = new Date(); 

      // Get the hours, minutes and seconds from the current time 
      var hours = now.getHours(); 
      var minutes = now.getMinutes(); 
      var seconds = now.getSeconds(); 

      // Format hours, minutes and seconds 
      if (hours < 10) { 
       hours = "0" + hours; 
      } 
      if (minutes < 10) { 
       minutes = "0" + minutes; 
      } 
      if (seconds < 10) { 
       seconds = "0" + seconds; 
      } 

      // Gets the element we want to inject the clock into 
      var elem = document.getElementById('clock'); 

      // Sets the elements inner HTML value to our clock data 
      elem.innerHTML = hours + ':' + minutes + ':' + seconds; 
     } 
    function start(){ 
     setInterval('updateClock()', 200); 
    } 
    </script> 

第一個函數計算我想要添加的milisecons,第二個函數是「活動時鐘」。我如何在第二個函數中實現第一個函數,以便獲得工作結果?

+0

可能重複(HTTP [添加小時爲Javascript Date對象?]://計算器。 COM /問題/ 1050720 /加小時到JavaScript的DAT電子對象) – CBroe

+0

你只需要'now.addHours(2)'。但是有更簡單的方法來爲日期添加小時。 – RobG

回答

2

看看這個fiddle

這裏可以使用class Date的構造函數Date(milliseconds)

以下是摘錄。

var now = new Date(); 
 
alert(now); 
 

 
var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000); 
 
var later = new Date(milliseconds); 
 
alert(later);

+0

你的問題解決了嗎? –

0

看看這個
fiddle here

var todayDate = new Date(); 
 
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)));

+0

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – secelite