使用 moment js 每 6 小时 UTC 重置一次的计数器
Counter that resets every 6 hours UTC using moment js
我在服务器上有一个 cron 作业 运行ning 每 6 小时 UTC 执行一些操作。
在客户端页面上,我想显示一个倒计时,显示下一个 cron 作业的剩余时间 运行。
如果是运行晚上午夜,我本可以完成
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now + 1000;
}
但我不知道如何针对 6 小时 UTC(上午 1200 点、上午 0600 点、下午 1200 点、上午 0600 点)执行此操作
倒数到其中任何一个
const getDates = () => {
const d = new Date()
const utcDate = new Date(Date.UTC(d.getFullYear(),d.getMonth(), d.getDate(),6,0,0))
return [utcDate,new Date(utcDate.getTime() + (21600000)),new Date(utcDate.getTime() + (21600000*2)),new Date(utcDate.getTime() + (21600000*3))]
}
console.log(getDates())
无需力矩即可轻松计算
const timeToNextRun = (start) => {
const sixHoursInMs = 6 * 3600 * 1000;
let remainingTime = sixHoursInMs - (start.getTime() % sixHoursInMs);
return remainingTime;
};
let now = new Date();
let countdown = timeToNextRun(now);
console.log(`Setting timer for ${countdown}ms - ${new Date(now.getTime() + countdown).toISOString()}`);
我在服务器上有一个 cron 作业 运行ning 每 6 小时 UTC 执行一些操作。
在客户端页面上,我想显示一个倒计时,显示下一个 cron 作业的剩余时间 运行。
如果是运行晚上午夜,我本可以完成
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now + 1000;
}
但我不知道如何针对 6 小时 UTC(上午 1200 点、上午 0600 点、下午 1200 点、上午 0600 点)执行此操作
倒数到其中任何一个
const getDates = () => {
const d = new Date()
const utcDate = new Date(Date.UTC(d.getFullYear(),d.getMonth(), d.getDate(),6,0,0))
return [utcDate,new Date(utcDate.getTime() + (21600000)),new Date(utcDate.getTime() + (21600000*2)),new Date(utcDate.getTime() + (21600000*3))]
}
console.log(getDates())
无需力矩即可轻松计算
const timeToNextRun = (start) => {
const sixHoursInMs = 6 * 3600 * 1000;
let remainingTime = sixHoursInMs - (start.getTime() % sixHoursInMs);
return remainingTime;
};
let now = new Date();
let countdown = timeToNextRun(now);
console.log(`Setting timer for ${countdown}ms - ${new Date(now.getTime() + countdown).toISOString()}`);