Search code examples
iosobjective-cnsdatenscalendar

Find weekday of a date given the month start weekday


If X = weekday that the month started on (for example, this month would be 4, or Wednesday)

Y = some other day of the month (for example, 21)

Find Z, which is the weekday (1-7) of Y

I thought this would work:

Z = (Y-X) % 7

In the example above Z = (21-4) % 7 = 3, which is correct (Oct. 21st is a Tuesday)

But it fails for November 8th: Z = (8-7) % 7 = 1, incorrect because Nov. 8th is a Saturday (weekday=7).

So what would be a robust formula for this?

Note - I know there are NSDate utilities for finding the weekday of a date, but in this case all I know is X,Y as given above.


Solution

  • It is hard to use modular arithmetic if you don't start counting from zero.

    So let's define some new variables:

    W = X - 1 = the weekday number, where W = 0 means Sunday

    D = Y - 1 = the day of the month, starting with 0

    Then W + D is the weekday number (Sunday = 0) of day D, if W + D < 7.

    So take (W + D) mod 7 to get the weekday number of day D. Add 1 to convert back to Sunday = 1, so ((W + D) mod 7) + 1.

    Substitute the definitions of W and D.

    Weekday number of day X (where Sunday = 1) = ((X - 1 + Y - 1) mod 7) + 1 = ((X + Y - 2) mod 7) + 1.