Code Snippet posted by:
Niladri.Biswas | Posted on: 7/27/2012 | Category:
C# Codes | Views: 344 | Status:
[Member] |
Points: 40
|
Alert Moderator
Given a StartDate in MM/DD/YYYY format , the challenge is to generate the date range in 6 months slot such that the program will stop at the current date.
class Program
{
static void Main(string[] args)
{
var startDate = "01/01/2011";
var endDate = DateTime.Now.ToString("MM/dd/yyyy");
var res = GetDateRange(Convert.ToDateTime(startDate), Convert.ToDateTime(endDate));
foreach (KeyValuePair<DateTime, DateTime> pair in res)
{
Console.WriteLine("StartDate = {0} , EndDate = {1}", pair.Key, pair.Value);
}
Console.ReadKey();
}
public static Dictionary<DateTime, DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
Dictionary<DateTime, DateTime> record = new Dictionary<DateTime,DateTime>();
int months = 6;
//case 1 if start date and end date diff less than 6 months
var res = MonthDifference(Convert.ToDateTime(endDate), Convert.ToDateTime(startDate));
if (res <= months)
{
record.Add(startDate, endDate);
}
//when date diff is greater than 6 months
else
{
var mod = res % months;
int counter = res % months == 0 ? (res / months) : (res / months) + 1;
int incr = 0;
for (int i = 0; i < counter; i++)
{
incr++;
if (incr != counter)
{
record.Add(startDate, startDate.AddMonths(months));
startDate = startDate.AddMonths(months).AddDays(1);
}
if (incr == counter)
{
record.Add(startDate, endDate);
}
}
}
return record;
}
public static int MonthDifference(DateTime lValue, DateTime rValue)
{
return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}
}
Best Regards,
Niladri Biswas