I\'m using the following query to get the next month.
int theMonth = ((System.DateTime)periodStartDate).Month+1;
But if the periodstartDate
after you compute theMonth
, check whether it equals to 13 (the month after December) and replace the value with 1:
theMonth = theMonth==13 ? 1 : theMonth;
DateTime nextMonthStartDate= DateTime.Parse(startdate.Year + "-" + startdate.AddMonths(1).Month + "-01");
This will work in leap year or non leap year. In the above converting strings to date time with static date 1 coz always taking start of the month. Hope it is useful
I like V4V's answer, but I write it this way:
DateTime dt = new DateTime(2011,12,2);
DateTime firstDayNextMonth = dt.AddMonths(1).AddDays(-dt.Day+1);
For example, I might be computing a future time and this code does that without stripping out the time part.
Per hvd's most astute comment, this code should be:
DateTime dt = new DateTime(2011,12,2);
DateTime firstDayNextMonth = dt.AddDays(-dt.Day+1).AddMonths(1);
DateTime date = DateTime.Now;
Console.WriteLine(date);
// Sunday 28.06.2015 г. 10:22:41 ч.
int monthsBack = -1;
int whichDay = 1;
// It means -> what day the first day of the previous month is.
DayOfWeek FirstDayOfWeek = date.AddMonths(monthsBack).AddDays(whichDay).DayOfWeek;
Console.WriteLine(FirstDayOfWeek);
// Friday
int delta = DayOfWeek.Monday - date.AddMonths(monthsBack).AddDays(whichDay).DayOfWeek;
Console.WriteLine(delta);
// -4
//-4 ->Monday , -3 ->Tuesday, -2 ->Wednesday , -1 ->Thursday, 0 ->Friday