如何以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;
}

其他回答

   const formatAMPM = (date) => {
    try {
      let time = date.split(" ");
      let hours = time[4].split(":")[0];
      let minutes = time[4].split(":")[1];
      hours = hours || 12;
      const ampm = hours >= 12 ? " PM" : " AM";
      minutes = minutes < 10 ? `${minutes}` : minutes;
      hours %= 12;
      const strTime = `${hours}:${minutes} ${ampm}`;
      return strTime;
    } catch (e) {
      return "";
    }
  };

const startTime = "2021-12-07T17:00:00.073Z"
formatAMPM(new Date(startTime).toUTCString())

使用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

试试这个

      var date = new Date();
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var seconds = date.getSeconds();
      var ampm = hours >= 12 ? "pm" : "am";

我的建议是使用moment js进行日期和时间操作。

https://momentjs.com/docs/#/displaying/format/

console.log(时刻)。格式(“hh: mm ')); < script src = " / / cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js " > < /脚本>