我正在处理一段代码,该代码需要在每次运行时显示时间。现在,当它需要为10:01:01时,它显示的时间为10:1:1。
如果我的分钟或秒数是<10,如何添加0?
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100;
color: #FFFFFF;
font-family: Open Sans;
font-weight: 700;
font-size: 24px;
background: #d70080;
}
div {
position: absolute;
top: 30%;
width: 100%;
text-align: center;
}
</style>
</head>
<body>
<script type="application/javascript">
function BroadSignPlay(){
var dd2 = new Date();var hh = dd2.getHours();var mm = dd2.getMinutes();var ss = dd2.getSeconds();
var data2 = "De tijd is nu: " + hh + ":" + mm + ":" + ss;
document.getElementById( "DivBroadSignPlay" ).innerHTML = data2;
}
if (top.location != location) {
top.location.href = location.href;
}
</script>
<div id="DivBroadSignPlay"> </div>
</body>
</html>
答案 0 :(得分:0)
使用String.prototype.padStart(2, '0')。要对数字进行字符串化以在其上呼叫padStart
,请先在其上呼叫toString()
,或使用模板字符串:
function showTime(){
const date = new Date();
const hh = date.getHours();
const mm = date.getMinutes();
const ss = date.getSeconds();
const str = [hh, mm, ss].map(x => `${x}`.padStart(2, '0')).join(':');
document.getElementById('time').innerHTML = str;
}
showTime();
setInterval(showTime, 1000);
<div id="time"></div>
答案 1 :(得分:-1)
要获取前导零,可以使用"0" + string
,然后使用带有负起始值-c
的{{3}}来获取最后的c
个字符。
function BroadSignPlay(){
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
var arr = [];
[hh,mm,ss].forEach(function(x){arr.push(getleadingZero(x))});
document.getElementById('DivBroadSignPlay').innerHTML = "De tijd is nu " + arr.join(':');
}
function getleadingZero(v) {
return ("0" + v).slice(-2);
}
setInterval(BroadSignPlay, 1000);
<div id="DivBroadSignPlay"></div>