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


当前回答

使用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以外的所有浏览器

其他回答

函数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) => {
    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())
<h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>



<script>
            var AM_or_PM = "AM";

            function startTime(){

                var today = new Date();
                var h = today.getHours();
                var m = today.getMinutes();
                var s = today.getSeconds();

                h = twelve_hour_time(h);
                m = checkTime(m);
                s = checkTime(s);



                document.getElementById('clock_display').innerHTML =
                    h + ":" + m + ":" + s +" "+AM_or_PM;
                var t = setTimeout(startTime, 1000);

            }

            function checkTime(i){

                if(i < 10){
                    i = "0" + i;// add zero in front of numbers < 10
                }
                return i;
            }

            // CONVERT TO 12 HOUR TIME. SET AM OR PM
            function twelve_hour_time(h){

                if(h > 12){
                    h = h - 12;
                    AM_or_PM = " PM";
                }
                return h;

            }

            startTime();

        </script>

希望这个答案比其他答案更容易理解(尤其是对新手来说)。

以下是我在一些站点中实现的解决方案,用于通知上次修改站点代码的时间。它通过date的选项参数实现AM/PM时间。toLocaleDateString(参见相关的Mozilla文档)。

// Last time page code was updated/changed
const options = {
    year: "numeric",
    month: "long",
    weekday: "long",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
    hour12: true // This is the line of code we care about here
    /*
        false: displays 24hs format for time
        true: displays 12, AM and PM format
    */
};

let last = document.lastModified;
let date = new Date(last);
let local = date.toLocaleDateString("en-US", options);
let fullDate = `${local}`;
document.getElementById("updated").textContent = fullDate;

输出的格式是:

Saturday, May 28, 2022, 8:38:50 PM

该输出然后显示在以下HTML代码中:

<p>Last update: <span id="updated">_update_date_goes_here</span></p>

注意:在这个用例中,是文档。lastModified有一些奇怪的行为,这取决于它是在本地运行还是在外部服务器上运行(参见这个堆栈溢出问题)。虽然当我在我的GitHub页面上运行它时,它可以正常工作(你应该在网站的页脚处看到它在运行)。

function getDateTime() {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();

  if (month.toString().length == 1) {
    month = '0' + month;
  }
  if (day.toString().length == 1) {
    day = '0' + day;
  }

  var hours = now.getHours();
  var minutes = now.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var timewithampm = hours + ':' + minutes + ' ' + ampm;

  var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
  return dateTime;
}