如何以12小时格式(AM/PM)显示JavaScript datetime对象?
当前回答
这是我的解决方案
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;
}
其他回答
下面是一种使用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()可能会根据区域/位置表现不同。
这是最简单的方法,你可以实现这使用三元操作符,或者你也可以使用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);
使用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)
查看Datejs。它们的内置格式化程序可以做到这一点:http://code.google.com/p/datejs/wiki/APIDocumentation#toString
这是一个非常方便的库,特别是如果您打算用date对象做其他事情时。
如果你只是想显示时间,那么…
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