Get difference in days between two weekdays

2019-04-28 13:10发布

问题:

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).

回答1:

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;