Skip to content

Instantly share code, notes, and snippets.

@bymyslf
Last active May 27, 2016 16:29
Show Gist options
  • Save bymyslf/d3769e8c096b764608ae9418ee243218 to your computer and use it in GitHub Desktop.
Save bymyslf/d3769e8c096b764608ae9418ee243218 to your computer and use it in GitHub Desktop.
DateTime extension methods
using System;
using System.Collections.Generic;
public static class DateTimeExtensions
{
public static bool IsBusinessDay(this DateTime date)
{
return date.DayOfWeek != DayOfWeek.Saturday
&& date.DayOfWeek != DayOfWeek.Sunday;
}
public static int BusinessDaysUntil(this DateTime from, DateTime to)
{
if (to < from)
{
DateTime aux = from;
from = to;
to = aux;
}
int businessDays = (to - from).Days + 1,
fullWeeksTotal = businessDays / 7,
intervalFirstDay = from.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)from.DayOfWeek,
intervalLastDay = to.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)to.DayOfWeek;
if (businessDays > (fullWeeksTotal * 7))
{
if (intervalFirstDay > intervalLastDay)
{
intervalLastDay += 7;
}
if (intervalFirstDay <= 6)
{
if (intervalLastDay >= 7) //Saturday and sunday are in the remaining interval
{
businessDays -= 2;
}
else if (intervalLastDay == 6) //Only saturday is in the remaining interval
{
businessDays -= 1;
}
}
else //Only sunday is in the remaining interval
{
businessDays -= 1;
}
}
//Remove weekend days
return (businessDays -= fullWeeksTotal * 2);
}
public static int BusinessDaysUntil(this DateTime from, DateTime to, IEnumerable<DateTime> holidays)
{
int businessDays = from.BusinessDaysUntil(to);
if (holidays != null)
{
from = from.Date;
to = to.Date;
DateTime current;
foreach (DateTime holiday in holidays)
{
current = holiday.Date;
if (current.IsBusinessDay() && current >= from && current <= to)
{
--businessDays;
}
}
}
return businessDays;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment