【问题标题】:Display 12-hour and 24-hour time显示 12 小时制和 24 小时制时间
【发布时间】:2014-11-20 12:51:30
【问题描述】:

我想制作一个显示当前时间的网页。单击“12 小时制”按钮时,div 区域会显示 12 小时制的时间。单击“24 小时制”按钮时,时间将在 div 区域中以 24 小时制显示。当前,单击这些按钮时没有任何反应。救命!

HTML:

<html>
<head>
<title>Clock</title>
<script type="text/javascript" src="clock.js"></script>
</head>
<body>
<div id="textbox"></div>
<br/>
<button type="radio" onclick="getTwelveHrs()">12 Hour Format</button>
<button type="radio" onclick="getTwentyFourHrs()">24 Hour Format</button>
</body>
</html>

JavaScript:

function getTwelveHours{
if (i < 10) {
    i = "0" + i;
}
return i;
}

function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('textbox').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
    startTime()
}, 500);
}
startTime();
}

function getTwentyFourHrs() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('textbox').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}

function checkTime(i) {
if (i<10) {i = "0" + i}; 
return i;
}

【问题讨论】:

  • getTwelveHrs 在一处或另一处拼写错误
  • 除了 Dale 说的,你还有一些语法错误。

标签: javascript jquery html datetime object


【解决方案1】:

你为什么不直接使用像 Moment.js 这样的库来为你做这件事。

http://momentjs.com/docs/

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

所以在使用 moment.js 时只需在 JavaScript 中使用这段代码

moment() 方法以您的特定格式返回当前日期。因此,当您用户单击按钮时,您可以在每个按钮上调用以下方法

moment().format("YYYY-MM-DD HH:mm"); // 24H clock
moment().format("YYYY-MM-DD hh:mm"); // 12H clock

没有测试过,但是应该可以的

【讨论】:

    【解决方案2】:

    12小时格式可以通过momentjs这个很好的库来获取时间&日期操作。

    moment().format('YYYY-MM-DD, hh:mm:ss A')

    其中 Post 或 ante meridiem (注意只有一个字符 a p 也被认为是有效的)

    Moment Js 链接:-

    https://momentjs.com

    【讨论】:

    • 我认为在 JavaScript Date 实例上调用 format 方法是无效的。
    • @matvs 是的,它应该是 moment() 而不是 new Date()。您发布了问题的几乎所有部分的答案,但是当按照 posr 中的代码显示 12 小时格式时没有 pm/am 。所以想添加与答案相同的内容。
    • 谢谢!!我没有意识到它是区分大小写的。
    【解决方案3】:

    同意其他人的意见,是的,该代码存在问题,但对于时间转换部分 - 也许您可以使用 JavaScript 内置函数执行类似这样的简单操作:

    12 小时制:

    let formattedTime = new Date().toLocaleTimeString('en-US');
    console.log(formattedTime)

    24 小时制:

    let currentDateTime = new Date();
        let formattedTime = currentDateTime.getHours() + ":" + currentDateTime.getMinutes() +":" + currentDateTime.getSeconds();
        console.log(formattedTime)

    【讨论】:

    • 您可以随时使用moment 一个很棒的包,但如果还没有导入它! & 不想要额外的包,那么你可以有机会在 .JS 中执行此操作。试试这些:let formattedTime = new Date().toLocaleTimeString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');,这用于填充到 2 位:const currentDateTime = new Date(); let formattedTime = ("0" + currentDateTime.getHours()).slice(-2) + ":" + ("0" + currentDateTime.getMinutes()).slice(-2) + ":" + ("0" + currentDateTime.getSeconds()).slice(-2);
    【解决方案4】:

    老实说,我不完全确定你是如何做到这一点的,但我想我理解你想要发生的事情。

    试试这个:

    window.onload = function() {
     var h, m, s;
     document.getElementById('twelveHrs').style.display = 'none';
     document.getElementById('twentyFourHrs').style.display = 'none';
     getTwelveHrs();
     getTwentyFourHrs();
    
     function getTwelveHrs() {
      var tag = 'AM';
      checkTime();
      if(h > 12) {
       h -= 12
       tag = 'PM';
      }
      document.getElementById('twelveHrs').innerHTML = h + ':' + m + ':' + s + ' ' + tag;
      t = setTimeout(function() {
       getTwelveHrs()
      }, 1000);
     }
    
     function getTwentyFourHrs() {
      checkTime();
      document.getElementById('twentyFourHrs').innerHTML = h + ':' + m + ':' + s;
      var t = setTimeout(function() {
       getTwentyFourHrs()
      }, 1000);
     }
    
     function checkTime() {
      var today = new Date();
      h = today.getHours();
      m = today.getMinutes();
      s = today.getSeconds();
      if(h < 10)
       h = '0' + h;
      if(m < 10)
       m = '0' + m;
      if(s < 10)
       s = '0' + s;
      return h, m, s;
     }
    }
    
    function displayTwelveHrs() {
     document.getElementById('twentyFourHrs').style.display = 'none';
     document.getElementById('twelveHrs').style.display = '';
    }
    
    function displayTwentyFourHrs() {
     document.getElementById('twelveHrs').style.display = 'none';
     document.getElementById('twentyFourHrs').style.display = '';
    }
    

    然后将您的 HTML 替换为:

    <div id="twelveHrs"></div>
    <div id="twentyFourHrs"></div>
    <br />
    <button type="radio" onclick="displayTwelveHrs()">12 Hour Format</button>
    <button type="radio" onclick="displayTwentyFourHrs()">24 Hour Format</button>
    

    基本上,当页面加载时,它会启动时钟并隐藏相应的div 标签。然后你点击一个按钮,它会显示你想要的div,同时隐藏另一个。

    可以在以下位置找到工作的 JSFiddle:http://jsfiddle.net/fp3Luwzc/

    【讨论】:

      【解决方案5】:

      由于工作的最后期限快到了,而且现在真的指日可待,我决定回答这个 5 年前的问题。

      大多数人建议使用 Moment.js 库,这非常好,因为在大多数情况下,重新发明轮子并没有任何意义,相信每周 npm 下载量为 9,897,199 的库毫无疑问是明智的选择。

      但是,由于提供基于 OP 代码的解决方案的唯一答案似乎存在一些错误;我想谦虚地提出我的解决方案:

      const FORMATS = {
        TwelveHours: 12,
        TwentyFourHours: 24
      }
      
      class Clock {
        format = FORMATS.TwentyFourHours;
      
        constructor(clockDivId) {
          this.clockDivId = clockDivId;
      
          this.clockInterval = setInterval(() => {
            document.getElementById(clockDivId).innerHTML = this.getCurrentTime().format(this.format);
          }, 500)
        }
      
        getCurrentTime() {
          let today = new Date();
          return new Time(today.getHours(), today.getMinutes(), today.getSeconds());
        }
      
        switchTo12HourFormat() {
          this.format = FORMATS.TwelveHours
        }
      
        switchTo24HourFormat() {
          this.format = FORMATS.TwentyFourHours
        }
      
        destroy() {
          clearInterval(this.clockInterval);
        }
      
      }
      
      class Time {
      
        constructor(hours, minutes, seconds) {
          this.hours = hours;
          this.minutes = minutes;
          this.seconds = seconds;
        }
      
        format(type) {
          switch (type) {
            case FORMATS.TwentyFourHours: {
              return this.print(this.hours)
            }
            case FORMATS.TwelveHours: {
              let tag = this.hours >= 12 ? 'p.m' : 'a.m';
              let hours = this.hours % 12;
              if (hours == 0) {
                hours = 12;
              }
              return this.print(hours) + ' ' + tag;
            }
      
          }
      
        }
      
        //private
        to2Digits(number) {
          return number < 10 ? '0' + number : '' + number;
        }
      
        print(hours) {
          return this.to2Digits(hours) + ':' + this.to2Digits(this.minutes) + ':' + this.to2Digits(this.seconds);
        }
      
      }
      
      let clock = new Clock("clock");
      <html>
      
      <head>
        <title>Clock</title>
      </head>
      
      <body>
        <div id="clock"></div>
        <br/>
        <button onclick="clock.switchTo12HourFormat()">12 Hour Format</button>
        <button onclick="clock.switchTo24HourFormat();">24 Hour Format</button>
      </body>
      
      </html>

      哦不,哦,分叉不!我写的是“print”而不是“this.print”,我已经在 Google Chrome 中运行了它。

      基本上 UI 被打印对话框阻塞了,我丢失了所有代码,不得不重新编写它,现在我要回家睡觉了,也许,也许是一集 HIMYM。

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 1970-01-01
        • 2018-04-13
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多