How do you display JavaScript datetime in 12 hour AM/PM format?

后端 未结 27 3101
慢半拍i
慢半拍i 2020-11-22 02:36

How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?

相关标签:
27条回答
  • 2020-11-22 03:23
    <h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>
    
    
    
    <script>
                var AM_or_PM = "AM";
    
                function startTime(){
    
                    var today = new Date();
                    var h = today.getHours();
                    var m = today.getMinutes();
                    var s = today.getSeconds();
    
                    h = twelve_hour_time(h);
                    m = checkTime(m);
                    s = checkTime(s);
    
    
    
                    document.getElementById('clock_display').innerHTML =
                        h + ":" + m + ":" + s +" "+AM_or_PM;
                    var t = setTimeout(startTime, 1000);
    
                }
    
                function checkTime(i){
    
                    if(i < 10){
                        i = "0" + i;// add zero in front of numbers < 10
                    }
                    return i;
                }
    
                // CONVERT TO 12 HOUR TIME. SET AM OR PM
                function twelve_hour_time(h){
    
                    if(h > 12){
                        h = h - 12;
                        AM_or_PM = " PM";
                    }
                    return h;
    
                }
    
                startTime();
    
            </script>
    
    0 讨论(0)
  • 2020-11-22 03:23
    function getDateTime() {
      var now = new Date();
      var year = now.getFullYear();
      var month = now.getMonth() + 1;
      var day = now.getDate();
    
      if (month.toString().length == 1) {
        month = '0' + month;
      }
      if (day.toString().length == 1) {
        day = '0' + day;
      }
    
      var hours = now.getHours();
      var minutes = now.getMinutes();
      var ampm = hours >= 12 ? 'pm' : 'am';
      hours = hours % 12;
      hours = hours ? hours : 12;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      var timewithampm = hours + ':' + minutes + ' ' + ampm;
    
      var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
      return dateTime;
    }
    
    0 讨论(0)
  • 2020-11-22 03:24

    Updated for more compression

    const formatAMPM = (date) => {
      let hours = date.getHours();
      let minutes = date.getMinutes();    
      const ampm = hours >= 12 ? 'pm' : 'am';
    
      hours %= 12;
      hours = hours || 12;    
      minutes = minutes < 10 ? `0${minutes}` : minutes;
    
      const strTime = `${hours}:${minutes} ${ampm}`;
    
      return strTime;
    };
    
    console.log(formatAMPM(new Date()));
    
    0 讨论(0)
提交回复
热议问题