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

后端 未结 27 3113
慢半拍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:14

    function formatTime( d = new Date(), ampm = true ) 
    {
        var hour = d.getHours();
        
        if ( ampm )
        {
            var a = ( hour >= 12 ) ? 'PM' : 'AM';
            hour = hour % 12;
            hour = hour ? hour : 12; // the hour '0' should be '12'  
        }
    
        var hour    = checkDigit(hour);  
        var minute  = checkDigit(d.getMinutes());
        var second  = checkDigit(d.getSeconds());
      
        // https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
        return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
    }
    
    function checkDigit(t)
    {
      return ( t < 10 ) ? `0${t}` : t;
    }
    
    document.querySelector("#time1").innerHTML = formatTime();
    document.querySelector("#time2").innerHTML = formatTime( new Date(), false );

    ampm true: (default)

    ampm false:

提交回复
热议问题