0

I am currently writing some code wherein there are 8 different pieces of text that are repeated over 8 weeks. In other words, week 1 - text 1, week 2 - text 2... and so on. This then just cycles indefinitely every 8 weeks. Lets say I know this particular week is week 8 and that is important, and I want to make some code using JavaScript that would establish this cycle so that even in 15 years time or whatever, it would still give me the correct result.

I am struggling to think of how I might do this. My guess is that it would involve doing some maths with getTime() to establish a number for exactly a week's worth of time, then somehow using this number plus the date from the start of this week to somehow establish a loop, that just keeps cycling through the eight texts. But I haven't really got the foggiest where I'd even start with this.

Any help would be greatly appreciated!

Laurens
  • 3
  • 1
  • Possibly a dup of the question containing this answer, but here's the useful bit, IMO: https://stackoverflow.com/a/31810991/294949 – danh Aug 19 '22 at 19:04
  • 1
    `weeksPassed = Math.floor((Date.now() - startDate) / 604800000);` – Thomas Aug 19 '22 at 19:11
  • "*establish a number for exactly a week's worth of time*" - that's simply `7*24*60*60*1000`. It might get more complicated if you want to consider daylight saving times, but I doubt you'll need that. – Bergi Aug 19 '22 at 22:20

1 Answers1

0

Decide when is your start date of week 1, then you can calculate date difference (divide by 7 for weeks) for any future date.

// set your starting date for week 1
const week1_start = new Date('2022-08-19');



function dateDiffInDays(a, b) {
  const _MS_PER_DAY = 1000 * 60 * 60 * 24;
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}


function get_week(week1_start, the_date) {
  var cycle = 8;
  var days = dateDiffInDays(week1_start, the_date);
  var weeks = Math.floor(days / 7);
  var week_num = ((weeks % cycle) + cycle) % cycle;
  return week_num
}

var test_date = new Date('2022-08-19');
for (var i = 0; i < 8 + 1; i++) {
  console.log(test_date.toString() + " is on week #" + (get_week(week1_start, test_date) + 1));
  test_date.setDate(test_date.getDate() + 7);
}
.as-console-wrapper {
max-height: 100% !important;

}

Function dateDiffInDays taken from this answer

IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Why `dateDiffInDays` when you could just write `dateDiffInWeeks` straight away? – Bergi Aug 19 '22 at 22:22
  • So that one could search for `dateDiffInDays` and find the source of the function in SO – IT goldman Aug 19 '22 at 22:24
  • If you copied it from another SO answer, you should provide proper attribution in a comment with a link, not by making the name "searchable". – Bergi Aug 19 '22 at 22:31