[英]How do I set the timer to show how much time is left for the day to end?
我想用这个计时器来显示巴西巴西利亚时间结束一天还有多少小时,我无法用 gethours 形成一些东西
{% assign productTags = product.tags %}
{% if productTags contains 'contador' %}
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.getHours();
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 29.5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
我可以用这段代码做到这一点吗?
解决这个问题的一种方法是使用备受喜爱的日期 API来确定今天和明天的日历日期。
您可以使用以下方法获取自纪元以来的今天日期(以毫秒为单位):
const now = new Date()
// Sun Dec 11 2022 13:21:03 GMT-XXXX (Your Time Zone)
然后你可以得到自 Epoch 以来的毫秒数
const nowMsSinceEpoch = now.getTime()
// 1670793708603
这是解决问题的基础。 如果你能找到今天的毫秒数和明天的 00:00,你可以比较两者:
let tomorrow = new Date()
tomorrow.setDate(now.getDate() + 1)
tomorow.setHours(0,0,0,0)
// Mon Dec 12 2022 00:00:00 GMT-XXXX (Your Time Zone)
在此阶段,您已准备好了解明天和今天的区别:
const differenceMs = tomorrow.getTime() - now.getTime()
通过从一个与纪元相关的时间戳中减去另一个与纪元相关的时间戳,您现在有了差异,并且您现在可以准确地计算出时间。 现在这只是一个算术问题。 您将需要确定一个小时内有多少毫秒,并且您将寻求您希望以何种方式对数字进行四舍五入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.