Skip to content

Instantly share code, notes, and snippets.

@icodeintx
Last active December 9, 2022 11:53
Show Gist options
  • Save icodeintx/4c75e72156238e0a4aa09cc62c707de7 to your computer and use it in GitHub Desktop.
Save icodeintx/4c75e72156238e0a4aa09cc62c707de7 to your computer and use it in GitHub Desktop.
BusinessDays and BusinessHourHours Extension methods for DateTime
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