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 remote after 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 = 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>

Solution 2:

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);

Post a Comment for "Format JavaScript Date As Hours:Minutes:Seconds"