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


当前回答

函数startTime() { const today = new Date(); let h = today.getHours(); let m = today.getMinutes(); let s = today.getSeconds(); Var子午线= h >= 12 ?pm: am; H = H % 12; H = H ?H: 12; M = M < 10 ?“0”+ m: m; S = S < 10 ?“0”+ s: s; var strTime = h +“:”+ m +”:“+ s + " " +子午线; . getelementbyid(的时间)。innerText = strTime; setTimeout(开始时间,1000); } 开始时间(); < h1 id = '时间' > < / h1 >

其他回答

函数formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); Var ampm =小时>= 12 ?'pm': 'am'; 小时=小时% 12; 小时=小时?时长:12小时;//小时'0'应该是'12' 分钟=分钟< 10 ?'0'+minutes: minutes; var strTime = hours + ':' + minutes + ' + ampm; 返回strTime; } console.log (formatAMPM(新日期));

更新以获得更多压缩

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()));

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>

en-US的短RegExp:

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

查看Datejs。它们的内置格式化程序可以做到这一点:http://code.google.com/p/datejs/wiki/APIDocumentation#toString

这是一个非常方便的库,特别是如果您打算用date对象做其他事情时。