I have a webservice which accepts the date range and due to huge data import i am passing the date range parameters for 1 month only.
Acceptable start date format : 1-apr-2012
Acceptable end date format : 30-apr-2012
I want programatically send each month’s start and end dates for last 2 years
like 1-Jan-2012 till 31-aug-2012
Below is sample piece of code which i started to test but its giving me span of 30 days when end date plus 1 month is added.
static void Main(string[] args)
{
string startDt = "1-apr-2011";
string endDt = "30-apr-2012";
DateTime dt = Convert.ToDateTime(startDt);
DateTime dt2 = Convert.ToDateTime(endDt);
CultureInfo culture = CultureInfo.GetCultureInfo("en-GB");
//Console.WriteLine(value.ToString("D", culture));
while (dt < dt2)
{
Console.WriteLine(dt.ToString("D", culture));
// Console.WriteLine(String.Format("{0:dd-MM-yyyy}", dt));
dt = dt.AddMonths(1);
}
Console.ReadLine();
}
Corrected Code:
static void Main(string[] args)
{
string startDt = "1-apr-2011";
string endDt = "30-apr-2012";
DateTime dt = Convert.ToDateTime(startDt);
DateTime dt2 = Convert.ToDateTime(endDt);
CultureInfo culture = CultureInfo.GetCultureInfo("en-GB");
while (dt < dt2)
{
DateTime dtend = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
Console.WriteLine(dt.ToString("D", culture));
Console.WriteLine(dtend.ToString("D", culture));
dt = dt.AddMonths(1);
}
Console.ReadLine();
}
Every month first date will be 1 but for last date you have to use
This takes month because month can be 28, 29, 30 or 31 days and takes year for leap year consideration.
Adding
AddMonth(1)to last date of a month does not necessary means it will give last date of next month.Picture this scenario
Now 30-Sept is last date of September but when we
AddMonth(1)it gives us 30-October. But last date of October is 31st not 30th.so if for January first date will be
while last date will be