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


当前回答

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 ); <p>ampm true: <span id="time1"></span> (default)</p> <p>ampm false: <span id="time2"></span></p>

其他回答

下面是一种使用regex的方法:

console.log(新日期(“7/10/2013 20:12:34”).toLocaleTimeString () .replace (/ ((\ d) +: \ d {2}) (: \ [d] {2 })(.*)/, "$ 1美元3”)) console.log(新日期(“7/10/2013 01:12:34”).toLocaleTimeString () .replace (/ ((\ d) +: \ d {2}) (: \ [d] {2 })(.*)/, "$ 1美元3”))

这将创建3个匹配组:

([\d]+:[\d]{2}) -小时:分钟 (:[\d]{2}) -秒 (.*) -空格和时段(时段是AM/PM的正式名称)

然后显示第1组和第3组。

警告:toLocaleTimeString()可能会根据区域/位置表现不同。

一个简短而甜蜜的实现:

// 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 d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return   d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;

使用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以外的所有浏览器

您可以使用这段简单的代码来确定am或PM

var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';