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

后端 未结 27 3100
慢半拍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 02:59

    var d = new Date();
    var hours = d.getHours() % 12;
      hours = hours ? hours : 12;
        var test = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(d.getMonth() + 1)] + " " + 
        ("00" + d.getDate()).slice(-2) + " " + 
        d.getFullYear() + " " + 
        ("00" + hours).slice(-2) + ":" + 
        ("00" + d.getMinutes()).slice(-2) + ":" + 
        ("00" + d.getSeconds()).slice(-2) + ' ' + (d.getHours() >= 12 ? 'PM' : 'AM'); 
        
    document.getElementById("demo").innerHTML = test;

提交回复
热议问题