2013-08-22 49 views
2

我有這樣的代碼,我不能得到第二次正確格式:格式的JavaScript日期時:分:秒

setInterval(function() { 
 
    var local = new Date(); 
 
    var localdatetime = local.getHours() + ":" + local.getMinutes() + ":" + local.getSeconds(); 
 

 
    var remote = new Date(); 
 
    var remotedatetime = remote.getHours() + ":" + remote.getMinutes() + ":" + remote.getSeconds(); 
 

 
    var remoteoffset = remote.setHours(local.getHours() - 5); 
 

 
    $('#local-time').html(localdatetime); 
 
    $('#remote-time').html(remoteoffset); 
 
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
My Time: 
 
<div id="local-time"></div> 
 
Their time: 
 
<div id="remote-time"></div>

local-time是完美的,顯示「HH:MM: ss「

remote-time只顯示隨機數列表。

我怎樣才能讓remote-time「hh:mm:ss」呢?

+0

remoteoffset.toString()? –

+0

你永遠不會處理所有可能的時區,使用UTC –

+0

_「遠程時間只顯示一個隨機數列表。」 - 它們不是隨機的,它們只是你所期望的格式。注意,在將其設置爲格式化值後,您從不使用'remotedatetime'變量? – nnnnnn

回答

6

要調整remote獲取其字符串表示,所以這就是做你沒有好。

然後你顯示的結果是setHours()(1970年1月1日以來的毫秒)而不是字符串。

這是我認爲你的目標爲:

setInterval(function() { 
 
    var local = new Date(); 
 
    var localdatetime = local.getHours() + ":" + pad(local.getMinutes()) + ":" + pad(local.getSeconds()); 
 

 
    var remote = new Date(); 
 
    remote.setHours(local.getHours() - 5); 
 
    var remotedatetime = remote.getHours() + ":" + pad(remote.getMinutes()) + ":" + pad(remote.getSeconds()); 
 

 
    $('#local-time').html(localdatetime); 
 
    $('#remote-time').html(remotedatetime); 
 
}, 1000); 
 

 
function pad(t) { 
 
    var st = "" + t; 
 
    
 
    while (st.length < 2) 
 
    st = "0" + st; 
 
    
 
    return st; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
My Time: 
 
<div id="local-time"></div> 
 
Their time: 
 
<div id="remote-time"></div>

0
setInterval(function() { 
    var local = new Date(); 
    var localdatetime = local.getHours() + ":" + local.getMinutes() + ":" + local.getSeconds(); 

    var remote = new Date(); 
    remote.setHours(local.getHours() - 5); 
    var remotedatetime = remote.getHours() + ":" + remote.getMinutes() + ":" + remote.getSeconds(); 

    $('#local-time').html(localdatetime); 
    $('#remote-time').html(remotedatetime); 
},1000);