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


当前回答

一个简短而甜蜜的实现:

// 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';
};

其他回答

在现代浏览器中,使用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 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())

我的建议是使用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 " > < /脚本>

这是最简单的方法,你可以实现这使用三元操作符,或者你也可以使用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);

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>