javascript - 带有 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 小时。非常感谢所有帮助
解决方案
您可能正在向后看 :-) 为什么不为午夜创建一个 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>
推荐阅读
- php - 类 Illuminate\Database\Eloquent\Builder 的对象无法转换为 int
- javascript - 我无法从 javascript 发布 json 对象
- c++ - 是否有适当的方法来根据编译时传递的模板值参数来别名类型(c ++)
- mysql - 仅当 endDate 不大于今天时如何获得结果
- javascript - 是否可以在对象模式中包含不同的键?
- python - 删除重复项而不更改二维列表中的顺序
- kdb - KDB/Q 我们如何计算移动中位数
- flutter - 颤振中Bloc中的ObservableList替换?
- r - 基于其他两个数据框创建一个额外的列
- html - 边距:自动;不垂直居中 div