I have a cron job running on the server that performs some action every 6 hours UTC.
On the client page, I want to show a countdown that shows the time remaining for the next cron job to run.
If it was running at midnight I could have done
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now 1000;
}
But I am not able to figure out how to do this for 6 hourly UTC (1200 AM, 0600 AM, 1200 PM, 0600 AM)
CodePudding user response:
You can calculate it quite easily without moment
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()}`);
CodePudding user response:
Just count down to any of these
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())