Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

82
Views
Counter that resets every 6 hours UTC using moment js

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)

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

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()}`);

7 months ago · Juan Pablo Isaza Report

0

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())

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs