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


当前回答

en-US的短RegExp:

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

其他回答

据我所知,在不进行扩展和复杂编码的情况下实现这一目标的最佳方式是这样的:

     date.toLocaleString([], { hour12: true});

Javascript AM/PM格式

<!DOCTYPE html> <html> <body> <p>Click the button to display the date and time as a string.</p> <button onclick="myFunction()">Try it</button> <button onclick="fullDateTime()">Try it2</button> <p id="demo"></p> <p id="demo2"></p> <script> function myFunction() { var d = new Date(); var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' }); document.getElementById("demo").innerHTML = n; } function fullDateTime() { var d = new Date(); var n = d.toLocaleString([], { hour12: true}); document.getElementById("demo2").innerHTML = n; } </script> </body> </html>

我查这个问题时发现的。

我如何使用.toLocaleTimeString()而不显示秒?

一个简短而甜蜜的实现:

// 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';
};
<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>
   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 d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->