CreativelyChris
CreativelyChris

Reputation: 93

Coding ISO Week of Year - Week 53 Problems

I'm trying to code a function to find the ISO week of the year. I found the ISO Week Wiki Page about it that included this Algorithm:

woy = (10 + doy − dow) div 7

It works for the most part, but I'm having two issues and not sure how to fix it.

Issue 1) Week 53's that really should be Week 1. (I.e. 20191230 to 20191231) Which come out as Week 53, but should be Week 1.

Issue 2) Week 53's of Leap Years. (I.e. 20210101 to 20210103) Which are coming out as Week 0, but should be Week 53.

Is there a clean way to alter/add to that formula to account for those above problems?

Upvotes: 1

Views: 1006

Answers (1)

trincot
trincot

Reputation: 350270

The cited Wikipedia article does include instructions for these boundary cases:

  • If the week number thus obtained equals 0, it means that the given date belongs to the preceding (week-based) year.
  • If a week number of 53 is obtained, one must check that the date is not actually in week 1 of the following year.

        enter image description here

The downside here is that you still need a function weeks. If you don't have that easily available, then here is another approach:

  1. Move the given date to match the Thursday in the same week. So for a Friday, Saturday or Sunday, you would go backwards, and for the other days (except Thursday) you would move forwards in time. Obviously the output for that Thursday should be same, since we stay in the same week.

  2. Apply the formula for that date. Obviously dow will always be 4 now (Thursday), so the formula simplifies to (6 + doy) div 7

Let's use this method on the examples you have given:

  • 30 December 2019 is a Monday, so we move forward to Thursday 2 January 2020. For that date, doy is 2, and the formula (6 + doy) div 7 gives 1 as result.

  • 1 January 2021 is a Friday, so we move backward to Thursday 31 December 2020. For that date, doy is 366, and the formula (6 + doy) div 7 gives 53 as result.

Upvotes: 2

Related Questions