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

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

    A short and sweet implementation:

    // returns date object in 12hr (AM/PM) format
    var formatAMPM = function formatAMPM(d) {
        var h = d.getHours();
        return (h % 12 || 12)
            + ':' + d.getMinutes().toString().padStart(2, '0')
            + ' ' + (h < 12 ? 'A' : 'P') + 'M';
    };
    

提交回复
热议问题