简体   繁体   English

显示 12 小时制和 24 小时制时间

[英]Display 12-hour and 24-hour time

I want to make a webpage that displays the current time.我想制作一个显示当前时间的网页。 When the "12-hour format" button is clicked, the time in 12-hour time will display in the div area.单击“12 小时格式”按钮时,div 区域将显示 12 小时制的时间。 When the "24-hour format" button is clicked, the time will show in 24-hour time in the div area.单击“24 小时格式”按钮时,时间将在 div 区域显示为 24 小时制。 Currently nothing happens when these buttons are clicked.当前单击这些按钮时没有任何反应。 Help!帮助!

HTML: 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: 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;
}

Why dont you just use a library like Moment.js to do this for you.为什么不使用像 Moment.js 这样的库来为你做这件事。

http://momentjs.com/docs/ http://momentjs.com/docs/

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

so just use this code in JavaScript when using moment.js所以在使用 moment.js 时只需在 JavaScript 中使用此代码

the moment() method returns the current date in your specific format. moment() 方法以您的特定格式返回当前日期。 So when you the user clicks the button you can call the following method on each button因此,当您用户单击按钮时,您可以在每个按钮上调用以下方法

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

Havn't tested this , but it should work没有测试过这个,但它应该可以工作

The 12 hour format can be obtained by using moment js a good library for performing time & date operations. 12 小时格式可以通过使用moment js 来获取,这是一个很好的执行时间和日期操作的库。

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

where Post or ante meridiem (Note the only one of the character ap are also considered valid) where Post 或 ante meridiem (注意只有一个字符 ap 也被认为是有效的)

Link for Moment Js :- Moment Js 的链接:-

https://momentjs.com https://momentjs.com

Agreed with others, yes issues with that code but for time conversion part - maybe you could do something simple like this using JavaScript built-in functions :同意其他人的意见,是的,该代码存在问题,但对于时间转换部分 - 也许您可以使用 JavaScript 内置函数执行这样的简单操作:

For 12-hr Format :对于 12 小时格式:

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

For 24-hr Format :对于 24 小时格式:

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

const time = new Date().getHours('en-US',{hour12:false});
const time = new Date().getHours('en-US',{hour12:true}); 

To be perfectly honest, I'm not entirely sure how you were trying to make this happen, but I think I understand what you wanted to have happen.老实说,我不完全确定您是如何努力实现这一目标的,但我想我理解您想要发生的事情。

Give this a try:试试这个:

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 = '';
}

Then replace your HTML with:然后将您的 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>

Basically, when the page loads, it'll start the clocks and hide the corresponding div tags.基本上,当页面加载时,它会启动时钟并隐藏相应的div标签。 Then you click a button, it will then display the div you want while hiding the other.然后你点击一个按钮,它会显示你想要的div ,同时隐藏另一个。

A working JSFiddle can be found at: http://jsfiddle.net/fp3Luwzc/可以在以下位置找到工作的 JSFiddle: http : //jsfiddle.net/fp3Luwzc/

Since deadline at work is coming and right now is really just around the corner, I have decided to answer this 5 years old question.由于工作截止日期即将到来,而且现在真的快到了,我决定回答这个 5 年前的问题。

Most people recommended using Moment.js library, which is really fine, because in most cases there is no point in reinventing the wheel and trusting a library with 9,897,199 weekly npm downloads is without any doubts a sane choice.大多数人推荐使用 Moment.js 库,这真的很好,因为在大多数情况下,重新发明轮子是没有意义的,相信每周有 9,897,199 次 npm 下载的库无疑是一个明智的选择。

However, since the only answer providing solution based on OP's code seems to have some bugs in it;但是,由于基于 OP 代码提供解决方案的唯一答案似乎存在一些错误; I would like to humbly propose my solution:我虚心提出我的解决方案:

 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 ? 'pm' : '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>

Oh no, oh forking no!哦不,哦不! I have written "print" instead of "this.print" and I've run it in Google Chrome.我已经写了“print”而不是“this.print”,我已经在谷歌浏览器中运行了它。

Basically UI got blocked by print dialog and I've lost all the code and had to write it again and now I am going home to enjoy some sleep and maybe, maybe one episode of HIMYM.基本上 UI 被打印对话框挡住了,我已经丢失了所有代码,不得不重新编写它,现在我要回家睡觉,也许,也许是一集 HIMYM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM