javascript - 函数逻辑对 javascript 时钟应用程序没有意义
问题描述
function showTime () {
let date = new Date();
let hours = date.getHours(); //0-23
let minutes = date.getMinutes(); //0-59
let seconds = date.getSeconds(); //0-59
let formatHours = convertFormat(hours);
hours = checkTime(hours);
hours = addZero(hours);
minutes = addZero(minutes);
seconds = addZero(seconds);
document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds + formatHours;
}
function convertFormat(time) {
let format = 'AM';
if (time >= 12) {
format = 'PM';
}
return format;
}
function checkTime(time) {
if (time > 12) {
time = time - 12;
}
if (time === 0) {
time = 12;
}
return time;
}
function addZero(time) {
if (time < 10) {
time = "0" + time;
}
return time;
}
showTime();
setInterval(showTime, 1000);
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: black;
}
#clock {
font-family: 'Orbitron';
font-size: 5rem;
color: limegreen;
}
<!DOCTYPE html>
<html>
<head>
<title>Clocck</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Orbitron" rel="stylesheet">
</head>
<body>
<div id="clock">
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
嘿伙计们,我目前正在开发一个简单的时钟应用程序。有一个特定的功能对我来说没有多大意义。convertFormat 函数的 if 语句将时间设置为等于 'PM' 如果它 >= 12。那么相反的情况发生在我身上。它的阅读时间是晚上 8 点 33 分?当它检查 hours 变量并读取 8 时,它应该将格式切换为 am? 对?
解决方案
当您看到时间是晚上 8:33 时,它仍然显示 PM 而不是 AM,因为 date.getHours() 函数将返回您的“系统时钟”,而不是您的函数显示的时钟值。这意味着当您错误地认为您的 convertFormat 函数的输入变量是“8”时,它实际上是系统时钟中的 20。
推荐阅读
- cordova - 安装`ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated`后无法构建我的Ionic项目
- python - 相同的命令但不同的结果,cmd和python子进程之间的奇怪行为
- libgdx - LibGDX / Box2D:如何跟踪身体之间的活动联系?
- arrays - 如何在反应中设置动态填充的选择选项的状态?TypeError:this.state.schoolName.map 不是函数
- python - 我想调整图像大小,但显示错误
- mysql - 如何处理 MySQL 错误:从 Oracle 迁移到 MySQL 期间出现 1071?
- ruby - 为什么使用和运算符不执行 rake 任务?
- reactjs - 无法在 reactjs 中发布数据(显示 400 BAD REQUEST)
- jmeter - Jmeter + Jenkins 性能插件
- c - GCC 在哪些目标平台上不支持标识符中的美元符号?