Changing the 1-24 hour to 1-12 hour for the “getHours()” Method

后端 未结 8 1364
温柔的废话
温柔的废话 2020-12-09 08:57

When I use the \"getHour()\" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me

相关标签:
8条回答
  • 2020-12-09 10:01
    function getClockTime(){
       var now    = new Date();
       var hour   = now.getHours();
       var minute = now.getMinutes();
       var second = now.getSeconds();
       var ap = "AM";
       if (hour   > 11) { ap = "PM";             }
       if (hour   > 12) { hour = hour - 12;      }
       if (hour   == 0) { hour = 12;             }
       if (hour   < 10) { hour   = "0" + hour;   }
       if (minute < 10) { minute = "0" + minute; }
       if (second < 10) { second = "0" + second; }
       var timeString = hour + ':' + minute + ':' + second + " " + ap;
       return timeString;
    }
    

    This Function will give the perfect time format in 1-12 hours

    0 讨论(0)
  • 2020-12-09 10:04

    the easy way to use this.

    setInterval(function() {
    
    var d = new Date();
    
    document.getElementById("demo").innerHTML = 
    d.getHours() % 12+" : "+d.getMinutes()+" : "+d.getSeconds();
    
    }, 1000);
    <p id="demo" ></p>

    0 讨论(0)
提交回复
热议问题