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


当前回答

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

其他回答

我发现它在这里工作得很好。

var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
 
 
var d       = new Date();
var hour    = d.getHours();  /* Returns the hour (from 0-23) */
var minutes     = d.getMinutes();  /* Returns the minutes (from 0-59) */
var result  = hour;
var ext     = '';
 
if(date_format == '12'){
    if(hour > 12){
        ext = 'PM';
        hour = (hour - 12);
        result = hour;

        if(hour < 10){
            result = "0" + hour;
        }else if(hour == 12){
            hour = "00";
            ext = 'AM';
        }
    }
    else if(hour < 12){
        result = ((hour < 10) ? "0" + hour : hour);
        ext = 'AM';
    }else if(hour == 12){
        ext = 'PM';
    }
}
 
if(minutes < 10){
    minutes = "0" + minutes; 
}
 
result = result + ":" + minutes + ' ' + ext; 
 
console.log(result);

这是活塞的例子

如果你把时间设置为字符串,输入var myTime = "15:30" 然后您可以使用下面的代码来获取am pm。

var hour = parseInt(myTime.split(":")[0]) % 12;
var timeInAmPm = (hour == 0 ? "12": hour ) + ":" + myTime.split(":")[1] + " " + (parseInt(parseInt(myTime.split(":")[0]) / 12) < 1 ? "am" : "pm");

如果你不需要打印上午/下午,我发现以下内容很好很简洁:

var now = new Date();
var hours = now.getHours() % 12 || 12;  // 12h instead of 24h, with 12 instead of 0. 

这是基于@bbrame的回答。

试试这个

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

您可以使用这段简单的代码来确定am或PM

var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';