gpt4 book ai didi

javascript - 我希望输出分钟和秒像 09 :09

转载 作者:行者123 更新时间:2023-11-28 19:26:36 25 4
gpt4 key购买 nike

// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));

// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance/1000/60)%60);
var seconds = Math.floor((distance /1000) % 60);

// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>

<p id="demo"></p>

</body>
</html>

我想要以分钟为单位输出 2 个数字,以秒为单位输出 2 个数字,例如 09:06

我试过 slice(-2) 但它没有正常工作,所以我想知道其他选项来尝试

我是 js 和这些东西的新手

最佳答案

只需检查它是否小于 10,如果小于则添加前导 0:

var minutes = (Math.floor((distance/1000/60)%60)<10?'0':'') + Math.floor((distance/1000/60)%60);
var seconds = (Math.floor((distance /1000) % 60)<10?'0':'') + Math.floor((distance /1000) % 60);

关于javascript - 我希望输出分钟和秒像 09 :09,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com