2

我有这段代码,我无法第二次正确格式化:

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”呢?

4

2 回答 2

6

你在得到它的字符串表示remote 正在调整,所以这对你没有好处。

然后,您将显示setHours()(milliseconds since January 1, 1970) 而不是字符串的结果。

这就是我认为您的目标:

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>

于 2013-08-22T21:44:45.073 回答
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);
于 2013-08-22T21:44:33.573 回答