0

Like Wordle, I’m trying to implement an algorithm to select a new element from an array everyday.

My current algorithm is as:

function getRandomElement(): string {
  const epochMS = new Date(2022, 0).valueOf();
  const now = Date.now();
  const msInDay = 86400000;
  const daysSinceEpochIndex = Math.floor((now - epochMS) / msInDay);

  return array[daysSinceEpochIndex % array.length];
}

The issue I’m facing is that while it work, epochMS has a different time zone than now due to daylight savings. This means it selects a new element from the array an hour after it should. How do I account for time zone differences and make it select a new element every 24 hours (i.e., at midnight) no matter where in the world the user is? Thank you.

  • Use `Date.UTC()`? – Jean-Baptiste Yunès Apr 10 '22 at 19:12
  • 1
    new Date() will always return the date with current timezone it is just the idea to get them based on miliSeconds from last date is just wrong why not just take the day of year instead for example an answer from here https://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366 the approved answer (the second snipper) – miyav miyav Apr 10 '22 at 20:24

0 Answers0