What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 61799 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > C# > Generate date range in 6 months slot ...
Niladri.Biswas

Generate date range in 6 months slot

 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
Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/21/2013 7:40:49 AM