将JavaScript日期格式设置为小时:分钟:秒

时间:2013-08-22 21:39:20

标签: javascript jquery

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

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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);