Tim Schmelter
Tim Schmelter

Reputation: 460158

Get difference in days between two weekdays

This sounds very easy, but i don't get the point.

So what's the easiest way to get number of days between two DayOfWeeks when the first one is the starting point? If the next weekday is earlier, it should considered to be in the next week.

The DayOfWeek-Enumeration starts with Sunday(0) and ends with Saturday(6).

 1. Monday    = 1
 2. Thursday  = 4

Result: 4 - 1 = 3

 1. Thursday  = 4
 2. Monday    = 1
// obviously a Math.Abs is helpful
Result: Math.Abs(1 - 4) = 3

But this result is wrong because there are 4 days between Thursday and Monday(next week).

Upvotes: 11

Views: 4486

Answers (1)

mbeckish
mbeckish

Reputation: 10579

Add 7, then mod 7:

(7 + (1 - 4)) % 7

For example:

var weekDay1  = DayOfWeek.Thursday;
var weeekDay2 = DayOfWeek.Monday;
var daysDiff  = (7 + (weeekDay2 - weekDay1)) % 7;

Upvotes: 33

Related Questions