Description

DateTime Class with several methods:

  • NumberOfBusinessDaysFrom
  • IsWorkDay
  • NextBusinessDay
  • PreviousBusinessDay

Code

public enum DatesType { Calendar = 0, Business = 1 };
 
public class DatesManager
{
#region Private Class Member Variable
 
private string _format = "MM/dd/yyyy";
private DateTime _date;
private DatesType _type;
private Hashtable _holidays;
 
#endregion
 
#region Constructor
 
public DatesManager()
{
init(DateTime.Now, DatesType.Calendar);
}
 
public DatesManager(string dateTime)
{
init(Convert.ToDateTime(dateTime), DatesType.Calendar);
}
 
public DatesManager(string dateTime, DatesType dateType)
{
init(Convert.ToDateTime(dateTime), dateType);
check();
}
 
#endregion
 
#region Public methods
 
public DatesType DateType
{
get { return _type; }
set
{
_type = value;
check();
}
}
 
public DateTime Date
{
get { return _date; }
set
{
_date = value;
check();
}
}
 
public bool IsHoliday
{
get
{
return _holidays.ContainsValue(_date.ToString(_format));
}
}
 
public bool IsWorkDay
{
get
{
return !(_date.DayOfWeek == DayOfWeek.Saturday || _date.DayOfWeek == DayOfWeek.Sunday);
}
}
 
public void AddHours(short hours)
{
_date = _date.AddHours(Convert.ToDouble(hours));
check();
}
 
public void AddDay()
{
_date = _date.AddDays(1.0);
check();
}
 
public void AddDays(short days)
{
_date = _date.AddDays(Convert.ToDouble(days));
check();
}
 
public void AddBusinessDays(short days)
{
double sign = Convert.ToDouble(Math.Sign(days));
int unsignedDays = Math.Sign(days) * days;
for (int i = 0; i < unsignedDays; i++)
{
do
{
_date = _date.AddDays(sign);
}
while (!this.IsWorkDay);
}
}
 
public DateTime NextBusinessDay()
{
DateTime date = _date;
do
{
date = date.AddDays(1.0);
}
while (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday);
return date;
}
 
public DateTime PreviousBusinessDay()
{
DateTime date = _date;
do
{
date = date.AddDays(-1.0);
}
while (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday);
return date;
}
 
public int NumberOfBusinessDaysFrom(DateTime date)
{
double dayToAdd = -1;
int numberOfBusinessDays = 0;
 
if (date < _date)
{
dayToAdd = 1;
}
while (_date != date)
{
date = date.AddDays(dayToAdd);
if (!(date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday ))
{
// if date is a working (business) day - increase a counter
numberOfBusinessDays++;
}
}
return numberOfBusinessDays;
}
 
#endregion
 
#region Private methods
 
private void init(DateTime dateTime, DatesType dateType)
{
_date = dateTime;
_type = dateType;
initHolidays();
}
 
private void initHolidays()
{
//Read holidays from .config file
_holidays = (Hashtable)ConfigurationSettings.GetConfig("Holidays");
}
 
private void check()
{
if (_type == DatesType.Business && !this.IsWorkDay)
{
_date = this.NextBusinessDay();
}
}
 
#endregion
}