Friday, May 30, 2014

Stupid code fragments, part one

I just discovered a surprisingly simple (and obvious in hindsight) algorithm for calculating the week index of a given date. For example, April 15th is in the 3rd week (or the 3rd Tuesday of the month).

I was going to do the usual thing and just Google for it but then I realized that the solution is extremely simple:

    private static int GetWeekPosition(DateTime date)
    {
      // the position of the given date is how many times I can subtract 7 days (go back one week) and still be in the same month
      // in other words, it's the integer part of (day / 7)
      return date.Day / 7;
    }

(I am returning a base-zero result, but you can of course add 1 if you need it.)

I realize this is not the answer to the Universe or anything but I thought it's interesting.

No comments: