Get the difference in days between two weekdays

It sounds very simple, but I do not understand.

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

DayOfWeek-Enumeration starts on Sunday(0) and ends on 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 incorrect, because between Thursday and Monday (next week) there are 4 days.

+4
source share
1 answer

Add 7, then mod 7:

 (7 + (1 - 4)) % 7 

For instance:

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

Source: https://habr.com/ru/post/1395677/


All Articles