date-arithmeticiso8601dayofweekweekdaynodatime

How do I calculate the next/previous ISO weekday number?


The ISO 8601 standard numbers weekdays 1 for Monday through to 7 for Sunday. Given a weekday number from 1 to 7, how do you calculate the number of the next/previous weekday?

E.g. given 1, the next weekday number would be 2, and the previous would be 7.


Solution

  • The weekday numbers can be calculated with simple addition and modulo. The formulas are as follows:

    Next weekday number

    (weekday number % 7) + 1

    Previous weekday number

    ((weekday number + 5) % 7) + 1


    Using C# and NodaTime's IsoDayOfWeek, you can create two simple extensions methods like:

    public static IsoDayOfWeek NextDay( this IsoDayOfWeek dayOfWeek ) => (IsoDayOfWeek)( (int)dayOfWeek % 7 + 1 );
    public static IsoDayOfWeek PreviousDay( this IsoDayOfWeek dayOfWeek ) => (IsoDayOfWeek)( (int)( dayOfWeek + 5 ) % 7 + 1 );