Created
March 27, 2014 10:43
-
-
Save jamescrowley/9804774 to your computer and use it in GitHub Desktop.
Calculate working days (per country)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static DateTime AddWorkingDays(this DateTime date, int workingDaysToAdd, string countryCode = null) | |
{ | |
return AddWorkingDays(date, workingDaysToAdd, (dateToTest) => IsWorkingDay(dateToTest, countryCode)); | |
} | |
public static DateTime AddWorkingDays(this DateTime date, int workingDaysToAdd, Func<DateTime,bool> isWorkingDay) | |
{ | |
var sign = Math.Sign(workingDaysToAdd); | |
var unsignedDays = Math.Abs(workingDaysToAdd); | |
for (var i = 0; i < unsignedDays; i++) | |
{ | |
do | |
{ | |
date = date.AddDays(sign); | |
} | |
while (!isWorkingDay(date)); | |
} | |
return date; | |
} | |
public static bool IsWorkingDay(this DateTime date, string countryCode = null) | |
{ | |
return !IsNonWorkDay(date.DayOfWeek, countryCode); | |
} | |
private static bool IsNonWorkDay(DayOfWeek day, string countryCode = null) | |
{ | |
switch (countryCode) | |
{ | |
case "DZ": // Algeria | |
case "BH": // Bahrain | |
case "BD": // Bangladesh | |
case "EG": // Egypt | |
case "IQ": // Iraq | |
case "IL": // Israel | |
case "JO": // Jordan | |
case "KW": // Kuwait | |
case "LY": // Libya | |
case "MV": // Maldives | |
case "MR": // Mauritania | |
case "OM": // Oman | |
case "QA": // Qatar | |
case "SA": // Saudi Arabia | |
case "SD": // Sudan | |
case "SY": // Syria | |
case "AE": // U.A.E. | |
case "YE": // Yemen | |
return day == DayOfWeek.Friday || day == DayOfWeek.Saturday; | |
case "AF": // Afghanistan | |
return day == DayOfWeek.Thursday || day == DayOfWeek.Friday; | |
case "IR": // Iran | |
return day == DayOfWeek.Friday; | |
case "NP": // Nepal | |
return day == DayOfWeek.Saturday; | |
case "BN": // Brunei Darussalam | |
return day == DayOfWeek.Friday || day == DayOfWeek.Sunday; | |
case "IN": // India | |
case "TH": // Thailand | |
return day == DayOfWeek.Sunday; | |
} | |
// most common Saturday/Sunday | |
return day == DayOfWeek.Saturday || day == DayOfWeek.Sunday; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment