Monday, June 20, 2011

Calculating monthwise leaves in date range in C#.NET

Recently there was an requirement at my work was finding the leave month wise.
Assume this way,If an employee apply leaves for the duration between 4th Feb,2011 and
4th July 2011.HR team wanted to calculate the month wise leave for that employee against total number of leave days.
By doing this way there is a room to not to calculate the "Week end" and other government announced holidays.

Here is the code for to do so.

class Program
{


static void Main(string[] args)
{
MonthChecker cObj = new MonthChecker();
List listDate = new List();


List strList = new List();

DateTime from = new DateTime(2011, 02, 25);
DateTime to = new DateTime(2011, 04, 14);


DateTime dt2 = new DateTime(2011,02,25);
DateTime to2 = new DateTime(2011, 06, 14);

string n = "";
string n1 = "";

while (from <= to)
{
from = from.AddDays(1);
DateTime d = new DateTime();
d = from.AddDays(-1);
if (cObj.CheckMonthLastDay(d))
{

listDate.Add(d);
}

}

for(int i=0;i
{

if (i == 0)
{
TimeSpan span = listDate[i].Subtract(dt2);
n = n + "\n" + span.Days.ToString();
strList.Add(n);
}

else
{
DateTime ck = new DateTime(listDate[i].Year, listDate[i].Month, 01);
TimeSpan spanck = listDate[i].AddDays(1).Subtract(ck);
string M = spanck.Days.ToString();
strList.Add(M);
}

}

foreach (string str in strList)
{
Console.WriteLine(str);
}
Console.ReadLine();

}
}

Class MonthChecker
{
public DateTime GetLastDayOfMonth(DateTime dtDate)
{

int a = DateTime.DaysInMonth(dtDate.Year, dtDate.Month);
DateTime dt = new DateTime(dtDate.Year, dtDate.Month, a);
return dt;

}
public bool CheckMonthLastDay(DateTime dtDate)
{
DateTime d1 = dtDate;
if (d1 == GetLastDayOfMonth(dtDate))
{
return true;
}
else
{
return false;
}
}

}