Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 457
Tim Schmelter Avatar asked Feb 09 '12 21:02

Tim Schmelter


1 Answers

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;
like image 113
mbeckish Avatar answered Nov 19 '22 16:11

mbeckish