Getting the current calendar week in Javascript

Topics: Javascript

I needed this code to create a TextExpander snippet that gives me the current calendar week in the format “3/2021”.

function ISO8601_week_no(dt) {
  var tdt = new Date(dt.valueOf());
  var dayn = (dt.getDay() + 6) % 7;
  tdt.setDate(tdt.getDate() - dayn + 3);
  var firstThursday = tdt.valueOf();
  tdt.setMonth(0, 1);
  if (tdt.getDay() !== 4) {
    tdt.setMonth(0, 1 + ((4 - tdt.getDay() + 7) % 7));
  }
  return 1 + Math.ceil((firstThursday - tdt) / 604800000);
}
date = new Date();
week = ISO8601_week_no(date);
year = date.getFullYear();
`${week}/${year}`;

Tags: Javascript