你如何在JavaScript中以12小时制(AM/PM)显示日期和时间?
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
console.log(formatAMPM(new Date));
minutes = ('0'+minutes).slice(-2);
,而不是这个写法:minutes = minutes < 10 ? '0'+minutes : minutes;
。 - VigneshtoLocaleString
,它可以以多种方式格式化 JS DateTime,包括你的情况。并且从古代时期起,所有浏览器都支持它 https://caniuse.com/?search=toLocaleString - Igor Lutsyk如果你只想显示小时,则..
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);
输出:上午7点
如果你想同时显示分钟...
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
);
输出:上午7:23
'numeric'
和 '2-digit'
搞混了。 - hon2a这里有一种使用正则表达式的方法:
console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
console.log(new Date('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()可能会根据区域/位置表现不同。
([\d]+:[\d]{2})
是我们感兴趣的部分。使用冒号作为分隔符,我们可以看到第一部分是 [\d]+
。加号意味着一个或多个。因此它正在寻找一个或多个数字(包括零)。如果您必须保证有一个零存在,那么它将是 (0[\d]:[\d]{2})
。现在这里的意思是,查找0加上另外一个数字,然后冒号,然后是其余部分。 - Steve Taubernew Date('7/10/2013 20:12:34').toLocaleTimeString()
返回 20:12:34
,而正则表达式只返回了 20:12
。@abhay-kumar 的答案 time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
起作用了。 - Craigo如果您不需要打印上午/下午,我发现以下方法简洁明了:
var now = new Date();
var hours = now.getHours() % 12 || 12; // 12h instead of 24h, with 12 instead of 0.
这是基于 @bbrame 的回答。
在现代浏览器中,使用Intl.DateTimeFormat
,并使用以下选项强制为12小时格式:
let now = new Date();
new Intl.DateTimeFormat('default',
{
hour12: true,
hour: 'numeric',
minute: 'numeric'
}).format(now);
// 6:30 AM
使用 default
将遵循浏览器的默认区域设置(如果添加了更多选项),但仍将输出12小时格式。
const time = new Date().toLocaleString([], { hour: 'numeric', minute: 'numeric' }); //"上午6:30"
- Dem Pilafian date.toLocaleString([], { hour12: true});
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date and time as a string.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="fullDateTime()">Try it2</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var d = new Date();
var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });
document.getElementById("demo").innerHTML = n;
}
function fullDateTime() {
var d = new Date();
var n = d.toLocaleString([], { hour12: true});
document.getElementById("demo2").innerHTML = n;
}
</script>
</body>
</html>
我在查看这个问题时发现了它。
使用 Moment.js 完成此操作
在 JavaScript 中使用以下代码,使用 moment.js
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)
我的建议是使用moment.js来进行日期和时间操作。
https://momentjs.com/docs/#/displaying/format/
console.log(moment().format('hh:mm a'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
更新以获得更高的压缩率
const formatAMPM = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
hours %= 12;
hours = hours || 12;
minutes = minutes < 10 ? `0${minutes}` : minutes;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
};
console.log(formatAMPM(new Date()));
使用 dateObj.toLocaleString([locales[, options]])
选项1 - 使用 locales
var date = new Date();
console.log(date.toLocaleString('en-US'));
选项2 - 使用选项
var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));
注意:目前支持所有浏览器,但不包括Safari。
警告:toLocaleTimeString() 的行为可能因地区/位置而异。
量好再切。 - Abandoned Cart