使用 javascript 添加 AM/PM

Adding AM/PM using javascript

本文关键字:PM AM 添加 javascript 使用      更新时间:2023-09-26

我有 12 小时格式化时间的简单代码

// This function gets the current time and injects it into the DOM
      function updateClock() {
                // Gets the current time
                var now = new Date();
                // Get the hours, minutes and seconds from the current time
                var hours = now.getHours();
                var minutes = now.getMinutes();
                var seconds = now.getSeconds();

                // Format hours, minutes and seconds
                if (hours > 12) {
                    hours = hours - 12;
                }
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }
                // Gets the element we want to inject the clock into
                var elem = document.getElementById('clock');
                // Sets the elements inner HTML value to our clock data
                elem.innerHTML = hours + ':' + minutes + ':' + seconds ;
            }

我想添加上午/下午请提前帮助我谢谢我只是JavaScript的初学者

编辑自己的代码后:

        // Get the hours, minutes and seconds from the current time
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        var amOrPm = 'AM';
        // Format hours, minutes and seconds
        if (hours > 12) {
            amOrPm = 'PM';
            hours = hours - 12;
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }
        // Gets the element we want to inject the clock into
        var elem = document.getElementById('clock');
        // Sets the elements inner HTML value to our clock data
        elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + amOrPm;

试试这个...

 var ampm = hours >= 12 ? 'pm' : 'am';

然后

elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
我不知道

你是否想自己编码,但有一个非常棒的库,它可以处理你能想象到的日期内容的所有内容。

只需结帐时刻。这是一个简单的 AF 库来转换日期(也在下午/上午)。

如果您有任何问题:)只是评论...