如何以12小时格式(AM/PM)显示JavaScript datetime对象?


当前回答

使用Moment.js

使用moment.js时,请在JavaScript中使用以下代码

H, HH       24 hour time
h, or hh    12 hour time (use in conjunction with a or A)

format()方法以特定格式返回日期。

moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)

其他回答

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; <p id="demo" ></p>

它将返回如下格式

09:56 AM

如果小时数小于10,则在start中添加0

这里使用的是ES6语法

const getTimeAMPMFormat = (date) => { let hours = date. gehours (); let minutes = date.getMinutes(); Const ampm =小时>= 12 ?' pm ': ' am '; 小时=小时% 12; 小时=小时?时长:12小时;//小时'0'应该是'12' 小时=小时< 10 ?'0' + hours:小时; //如果hours小于10,则在开始时添加0 分钟=分钟< 10 ?'0' + minutes: minutes; 返回小时+ ':' +分钟+ ' ' + ampm; }; console.log (getTimeAMPMFormat(新日期));// 09:59 am

一个简短而甜蜜的实现:

// 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';
};

我发现它在这里工作得很好。

var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
 
 
var d       = new Date();
var hour    = d.getHours();  /* Returns the hour (from 0-23) */
var minutes     = d.getMinutes();  /* Returns the minutes (from 0-59) */
var result  = hour;
var ext     = '';
 
if(date_format == '12'){
    if(hour > 12){
        ext = 'PM';
        hour = (hour - 12);
        result = hour;

        if(hour < 10){
            result = "0" + hour;
        }else if(hour == 12){
            hour = "00";
            ext = 'AM';
        }
    }
    else if(hour < 12){
        result = ((hour < 10) ? "0" + hour : hour);
        ext = 'AM';
    }else if(hour == 12){
        ext = 'PM';
    }
}
 
if(minutes < 10){
    minutes = "0" + minutes; 
}
 
result = result + ":" + minutes + ' ' + ext; 
 
console.log(result);

这是活塞的例子

en-US的短RegExp:

var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"