显示12小时和24小时时间 [英] Display 12-hour and 24-hour time

查看:182
本文介绍了显示12小时和24小时时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. When the "24-hour format" button is clicked, the time will show in 24-hour time in the div area. Currently nothing happens when these buttons are clicked. Help!

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


推荐答案

为什么不只使用像Moment.js这样的库来为您完成此任务。

Why dont you just use a library like Moment.js to do this for you.

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中使用此代码

so just use this code in JavaScript when using moment.js

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

the moment() method returns the current date in your specific format. 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

这篇关于显示12小时和24小时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆