Last active
December 9, 2022 11:53
-
-
Save icodeintx/4c75e72156238e0a4aa09cc62c707de7 to your computer and use it in GitHub Desktop.
BusinessDays and BusinessHourHours Extension methods for DateTime
This file contains hidden or 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.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace DateTimeExtensionTest | |
{ | |
public static class DateTimeExtensions | |
{ | |
public static int GetBusinessDays(this DateTime startDate, DateTime endDate, IEnumerable<DateTime> holidays) | |
{ | |
if (startDate > endDate) | |
{ | |
throw new NotSupportedException("ERROR: [startDate] cannot be greater than [endDate]."); | |
} | |
int cnt = 0; | |
for (var current = startDate; current < endDate; current = current.AddDays(1)) | |
{ | |
if (current.DayOfWeek != DayOfWeek.Saturday && current.DayOfWeek != DayOfWeek.Sunday && (holidays != null && !holidays.Contains(current.Date))) | |
{ | |
cnt++; | |
} | |
} | |
return cnt; | |
} | |
public static int GetBusinessHours(this DateTime startDate, DateTime endDate, IEnumerable<DateTime> holidays) | |
{ | |
if (startDate > endDate) | |
{ | |
throw new NotSupportedException("ERROR: [startDate] cannot be greater than [endDate]."); | |
} | |
int cnt = -1; | |
for (var current = startDate; current < endDate; current = current.AddHours(1)) | |
{ | |
if (current.DayOfWeek != DayOfWeek.Saturday && current.DayOfWeek != DayOfWeek.Sunday && (holidays != null && !holidays.Contains(current.Date))) | |
{ | |
cnt++; | |
} | |
} | |
return cnt; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment