Display 12-hour and 24-hour time

后端 未结 5 1545
猫巷女王i
猫巷女王i 2021-02-14 10:30

I want to make a webpage that displays the current time. When the \"12-hour format\" button is clicked, the time in 12-hour time will display in the div area. When the \"24-hour

5条回答
  •  后悔当初
    2021-02-14 11:25

    To be perfectly honest, I'm not entirely sure how you were trying to make this happen, but I think I understand what you wanted to have happen.

    Give this a try:

    window.onload = function() {
     var h, m, s;
     document.getElementById('twelveHrs').style.display = 'none';
     document.getElementById('twentyFourHrs').style.display = 'none';
     getTwelveHrs();
     getTwentyFourHrs();
    
     function getTwelveHrs() {
      var tag = 'AM';
      checkTime();
      if(h > 12) {
       h -= 12
       tag = 'PM';
      }
      document.getElementById('twelveHrs').innerHTML = h + ':' + m + ':' + s + ' ' + tag;
      t = setTimeout(function() {
       getTwelveHrs()
      }, 1000);
     }
    
     function getTwentyFourHrs() {
      checkTime();
      document.getElementById('twentyFourHrs').innerHTML = h + ':' + m + ':' + s;
      var t = setTimeout(function() {
       getTwentyFourHrs()
      }, 1000);
     }
    
     function checkTime() {
      var today = new Date();
      h = today.getHours();
      m = today.getMinutes();
      s = today.getSeconds();
      if(h < 10)
       h = '0' + h;
      if(m < 10)
       m = '0' + m;
      if(s < 10)
       s = '0' + s;
      return h, m, s;
     }
    }
    
    function displayTwelveHrs() {
     document.getElementById('twentyFourHrs').style.display = 'none';
     document.getElementById('twelveHrs').style.display = '';
    }
    
    function displayTwentyFourHrs() {
     document.getElementById('twelveHrs').style.display = 'none';
     document.getElementById('twentyFourHrs').style.display = '';
    }
    

    Then replace your HTML with:


    Basically, when the page loads, it'll start the clocks and hide the corresponding div tags. Then you click a button, it will then display the div you want while hiding the other.

    A working JSFiddle can be found at: http://jsfiddle.net/fp3Luwzc/

提交回复
热议问题