首页 > 解决方案 > 函数逻辑对 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? 对?

标签: javascript

解决方案


当您看到时间是晚上 8:33 时,它仍然显示 PM 而不是 AM,因为 date.getHours() 函数将返回您的“系统时钟”,而不是您的函数显示的时钟值。这意味着当您错误地认为您的 convertFormat 函数的输入变量是“8”时,它实际上是系统时钟中的 20。


推荐阅读