首页 > 解决方案 > 带有 UTC 偏移量的 Jquery 计时器

问题描述

function getMinutesUntilNextHour() {
    var now = new Date();
    var hours = now.getUTCHours();
    var mins = now.getMinutes();
    var secs = now.getSeconds();

    // Compute time remaining per unit
    var cur_hours = 23 - hours;
    var cur_mins = 60 - mins;
    var cur_secs = 60 - secs;

    // Correct zero padding of hours if needed
    if (cur_hours < 10) {
        cur_hours = '0' + cur_hours;
    }
    // Correct zero padding of minutes if needed
    if (cur_mins < 10) {
        cur_mins = '0' + cur_mins;

这是一个简单的 24 小时倒计时计时器的代码,它每 24 小时后再次重置,但是当我在计算剩余时间部分添加 11 小时时,它偶尔会根据当前的 UTC 向我抛出负时间(以小时为单位)时间。我只想从不同的时间/时区开始 24 小时。非常感谢所有帮助

标签: javascriptjquery

解决方案


您可能正在向后看 :-) 为什么不为午夜创建一个 Date 对象,然后从中减去当前时间。此示例适用于本地时区,但您可以轻松地将其调整为 UTC 或其他时区。

// We're going to use Vue to update the page each time our counter changes.
// You could also do this old style, updating the DOM directly.
// vueStore is just a global variable that will contain the current time, 
// and the function to periodically update it.
var vueStore = { 
now: new Date(),
  countdown(){
    vueStore.now = new Date();
    window.setTimeout(() => {this.countdown(); }, 1000);
  }
};
vueStore.countdown();


var vm = new Vue({
    el: "#vueRoot",
    data: { vueStore: vueStore },
    computed: {
        timeTilMidnight() {
            var midnightTonight = new Date(this.vueStore.now.getYear(), this.vueStore.now.getMonth(), this.vueStore.now.getDay() + 1);
            var timeToMidnight = midnightTonight.getTime() - this.vueStore.now.getTime();

            return new Date(timeToMidnight).toLocaleTimeString([], {
                timeZone: "UTC"
            });
        }
    }
});
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<div id="vueRoot">
<h1>{{timeTilMidnight}}</h1>
</div>


推荐阅读