Created
September 20, 2011 05:39
-
-
Save maddievision/1228429 to your computer and use it in GitHub Desktop.
AddWorkingDays C# With Holidays Support
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
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace ReportAutomation | |
{ | |
public static class DateMath | |
{ | |
public static DateTime AddWorkingDays(this DateTime input, int interval, List<DateTime> holidays = null) | |
{ | |
bool hasHolidays = (holidays != null); | |
DateTime cursor = input; | |
int nextHolidayIndex = 0; | |
int daysNextHoliday = -1; | |
int daysNextWeekend = -1; | |
int nbdAdd = 0; | |
int nbdAdd2 = 0; | |
bool adjust = false; | |
while (cursor.DayOfWeek == DayOfWeek.Saturday || cursor.DayOfWeek == DayOfWeek.Sunday || | |
(hasHolidays && holidays.FindIndex(item => item.Equals(cursor)) != -1)) | |
{ | |
cursor = cursor.AddDays(1); | |
adjust = true; | |
} | |
if (adjust && interval > 0) interval--; | |
if (hasHolidays) | |
{ | |
nextHolidayIndex = holidays.FindIndex(item => item >= cursor); | |
if (nextHolidayIndex == -1) | |
{ | |
hasHolidays = false; | |
} | |
else | |
{ | |
daysNextHoliday = holidays[nextHolidayIndex].Subtract(cursor).Days; | |
} | |
} | |
do { | |
daysNextWeekend = (cursor.DayOfWeek == DayOfWeek.Sunday)?0:(DayOfWeek.Saturday - cursor.DayOfWeek); | |
if (hasHolidays && daysNextHoliday < 0) | |
{ | |
nextHolidayIndex++; | |
if (nextHolidayIndex >= holidays.Count) | |
{ | |
hasHolidays = false; | |
} | |
else | |
{ | |
daysNextHoliday = holidays[nextHolidayIndex].Subtract(cursor).Days; | |
} | |
} | |
if (hasHolidays && (daysNextHoliday < daysNextWeekend)) | |
{ | |
nbdAdd = daysNextHoliday; | |
nbdAdd2 = 1; | |
} | |
else | |
{ | |
nbdAdd = daysNextWeekend; | |
nbdAdd2 = 2; | |
} | |
if (nbdAdd <= interval) | |
{ | |
if (hasHolidays) daysNextHoliday -= nbdAdd + nbdAdd2; | |
cursor = cursor.AddDays(nbdAdd + nbdAdd2); | |
interval -= nbdAdd; | |
} | |
else | |
{ | |
cursor = cursor.AddDays(interval); | |
interval = 0; | |
} | |
} while (interval > 0 || (hasHolidays && daysNextHoliday == 0) || daysNextWeekend == 0); | |
return cursor; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works fast enough for my needs however would be great if it could be optimised.