0

If the user sets a date on the backend (via jQuery DateTimer Picker) the following acf_vars.timer variable would look like this on the frontend:

2021 2 9 13 08 00

I have the following construct as a countdown timer (CODEPEN):

const [y, month, d, h, minute, s] = acf_vars.timer.split(' ');

// monthIndex in Date Object begins with 0, so we subtract 1
const countDownDate = new Date(y, month - 1, d, h, minute, s).getTime();

const updateCountdown = () => {
    const now = new Date().getTime(); // Get today's date and time
    const distance = countDownDate - now; // Find distance between now and the countdown date
    const expiredTimer = distance <= 0;

    let days = Math.floor(distance / (1000 * 60 * 60 * 24));
    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

    if (expiredTimer) {
        days = hours = minutes = seconds = 0;
        clearInterval(timerInterval);
    }

    document.querySelectorAll('.ticker').forEach((container) => {
        container.children[0].classList.contains('days') &&
            (container.children[0].textContent = days);
        container.children[2].classList.contains('hours') &&
            (container.children[2].textContent = hours);
        container.children[4].classList.contains('minutes') &&
            (container.children[4].textContent = minutes);
        container.children[6].classList.contains('seconds') &&
            (container.children[6].textContent = seconds);
    });
};

const timerInterval = setInterval(updateCountdown, 1000);

updateCountdown();

If the user doesn't specify a future date on the backend, I'd like to use a fallback which automatically sets the countdown timer to the upcoming Sunday at 9am. To solve this I tried setting a standardized countDownDate variable but I'm having trouble coming up with a way to set the day and time to automatically be the upcoming Sunday at 9am.

2 Answers 2

0

It seems you just want a way to set a date to next Sunday at 09:00. In plain JS it might be:

/* Get a date for next occurence of Sunday at 09:00
 *
 * @param {Date} d - start date, default is current date and time
 * @returns {Date} for next Sunday at 09:00 after d
 */
function getNextSunday(d = new Date()) {
  // Create date for next Sun at 9
  let sun = new Date(d.getFullYear(), d.getMonth(), d.getDate() + (7 - (d.getDay() || 7)), 9, 0, 0, 0);
  // If date is same day but later, move to next Sun
  sun <= d? sun.setDate(sun.getDate() + 7) : null;
  return sun;
}

// Examples
// Next Sunday at 9:00
console.log(getNextSunday().toString());
// Next Sunday after Sun 7 Feb at 8:59:59
console.log(getNextSunday(new Date(2021, 1, 7, 8, 59, 59)).toString());
// Next Sunday after Sun 7 Feb at 9:00
console.log(getNextSunday(new Date(2021, 1, 7, 9)).toString());

Notes:

  1. d.getDay() || 7 is used so that if getDay returns 0 (Sunday), it's replaced with the number 7. That means the expression sets sun to the current day if it's Sunday or the next Sunday if it isn't. Otherwise on Sundays it would create a Date for the previous Sunday.

  2. sun <= d? sun.setDate(sun.getDate() + 7) : null is used so that if the current date is Sunday but the time is after the specified time (in this case 9:00) the date is moved to the following Sunday at 9:00. Using the compound ? : operator this way is just a another way of writing if (sun <= d) sun.setDate(sun.getDate() + 7) on one line. I prefer if statements to be followed by a block and would rather use ? : for simple expressions on single lines.

1
  • This is a great vanilla solution. Two questions: could you explain when and why the OR operator in (d.getDay() || 7)) would be important? Since d.getDay() will always return something why are we including this? And would you be able to explain what you mean by If date is same day but later, move to next Sun? I think your comments already provide great insight, I just want to make sure I fully understand the concept at use. Thank you!
    – Hewe
    Commented Jan 25, 2021 at 16:20
0

Moment.js might be what you are looking for.

moment().endOf('week').add(1, 'second').add(9, 'hours').toString()

End of week uses the locale aware week start day, so you might have to configure it if you have users globally.

Edit

Alternatively, if you do not want to use external libraries you can check the current weekday and hour with the JavaScript Date object.

const day = countDownDate.getDay() // weekday sun = 0, sat = 6
const hour = countDownDate.getHours() // 0 - 23

Within your logic, you would want to get the distance between day and 0 (also accounting for countDownDate starting on a Sunday) and hour and 9. However, another way to implement this is to check the current date upon each update which could reduce the error in case the interval gets interrupted.

3
  • Thank you for the pointer. Do you think it would be worth the effort to disassemble the used methods if I didn't want to use the moment library?
    – Hewe
    Commented Jan 22, 2021 at 19:23
  • Sure, I updated my answer. I thought you would be interested in moment.js since you were already using jquery.
    – iolibitz
    Commented Jan 22, 2021 at 20:00
  • "End of week uses the locale aware week start day" which means you have no idea what it will be. If the intention is to set it to Sunday of the Gregorian calendar, then do exactly that.
    – RobG
    Commented Jan 22, 2021 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.