ThatChrisGuy
ThatChrisGuy

Reputation: 90

Determine the "Cycle" and week with JavaScript

I use a project calendar at work that uses 4 week cycles starting with the first Saturday of the year.

How can I determine the cycle and week of the cycle for a given date using JavaScript without any extra libraries?

Upvotes: 0

Views: 243

Answers (1)

user3717023
user3717023

Reputation:

This isn't specific to Apps Script, the Date object works in GAS the same as in most browsers (except some parsing details which are not relevant here). You can get the first day of year, determine how far it is from first Saturday, find first Saturday, then find the number of days after it.

After that, dividing by 28 and flooring gives the number of current cycle; I add 1 assuming it's 1-based numbering, but that's up to you. Similarly with week number, except also % 4 is used to reset the counter every 4 weeks.

The current date, 2016-06-25, begins the 2nd week of the 7th cycle of the year.

The dates preceding the first Saturday of the year are recorded as "0th cycle, 0th week"; a matter of convention.

function weeks() {
  var now = new Date();
  var year = now.getFullYear();
  var offsetSat = 6 - new Date(year, 0, 1).getDay();
  var firstSat = new Date(year, 0, 1 + offsetSat);
  var daysSince = Math.round((now - firstSat)/(24*3600*1000));
  var cycleNum = daysSince < 0 ? 0 : 1 + Math.floor(daysSince/28);
  var weekNum = daysSince < 0 ? 0 : 1 + Math.floor(daysSince/7) % 4;
  return [cycleNum, weekNum];
}

Upvotes: 3

Related Questions