【问题标题】:Adding AM/PM using javascript [duplicate]使用 javascript 添加 AM/PM [重复]
【发布时间】:2016-11-12 09:35:21
【问题描述】:

我有 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 的初学者

【问题讨论】:

  • 这里有一个提示:如果你必须减去 12 小时,那就是下午。否则,就是 AM。

标签: javascript


【解决方案1】:

编辑自己的代码后:

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

【讨论】:

    【解决方案2】:

    试试这个...

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

    然后

    elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
    

    【讨论】:

    • 它现在可以工作了,非常感谢
    【解决方案3】:

    我不知道你是否想自己编写代码,但是有一个非常棒的库,可以处理你能想象到的所有日期。

    只需结帐momentjs。 这是一个简单的 AF 库来转换日期(也在 pm/am 中)。

    如果您有任何问题 :) 只需发表评论...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 2019-01-13
      • 2012-08-31
      相关资源
      最近更新 更多