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


当前回答

这是最简单的方法,你可以实现这使用三元操作符,或者你也可以使用if else代替!

const d = new Date();
let hrs = d.getHours();
let m = d.getMinutes();
// Condition to add zero before minute
let min = m < 10 ? `0${m}` : m;
const currTime = hrs >= 12 ? `${hrs - 12}:${min} pm` : `${hrs}:${min} am`;
console.log(currTime);

其他回答

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>

这里有另一种简单有效的方法:

        var d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->

这是我的解决方案

function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
    strampm= "PM";
} else {
    strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
    hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}

function checkTimeAddZero(i) {
if (i < 10) {
    i = "0" + i
}
return i;
}

使用dateObj。toLocaleString([地区[选项]])

选项1 -使用区域设置

var date = new Date();
console.log(date.toLocaleString('en-US'));

选项2 -使用选项

var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));

注:支持除safari atm以外的所有浏览器

如果你只是想显示时间,那么…

var time = new Date(); console.log ( 时间。toLocaleString('en-US',{小时:'数字',小时12:true}) );

输出:早上7点

如果你也想显示会议纪要,那么……

var time = new Date(); console.log ( 时间。toLocaleString('en-US',{小时:'数字',分钟:'数字',小时12:true}) );

输出:早上7:23