Skip to content Skip to sidebar Skip to footer

Format Javascript Date As Hours:minutes:seconds

I have this code and I cannot get the second time to format properly: local-time is perfect and displays 'hh:mm:ss' remote-time just displays a list of random numbers. How can I m

Solution 1:

You're adjusting remoteafter getting its string representation, so that's doing you no good.

Then you're displaying the result of setHours() (milliseconds since January 1, 1970) rather than the string.

This is what I think you're aiming for:

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

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

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

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

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

Solution 2:

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

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

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

Post a Comment for "Format Javascript Date As Hours:minutes:seconds"