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


当前回答

试试这个

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

其他回答

它将返回如下格式

09:56 AM

如果小时数小于10,则在start中添加0

这里使用的是ES6语法

const getTimeAMPMFormat = (date) => { let hours = date. gehours (); let minutes = date.getMinutes(); Const ampm =小时>= 12 ?' pm ': ' am '; 小时=小时% 12; 小时=小时?时长:12小时;//小时'0'应该是'12' 小时=小时< 10 ?'0' + hours:小时; //如果hours小于10,则在开始时添加0 分钟=分钟< 10 ?'0' + minutes: minutes; 返回小时+ ':' +分钟+ ' ' + ampm; }; console.log (getTimeAMPMFormat(新日期));// 09:59 am

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

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>

使用Moment.js

使用moment.js时,请在JavaScript中使用以下代码

H, HH       24 hour time
h, or hh    12 hour time (use in conjunction with a or A)

format()方法以特定格式返回日期。

moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)

下面是解决方案

var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return   d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;