具有UTC偏移量的jQuery计时器

时间:2018-10-22 06:53:33

标签: javascript 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小时可以从不同的时区开始。感谢所有帮助

1 个答案:

答案 0 :(得分:0)

您可能正在向后看:-)为什么不为午夜创建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>