I\'m using the following query to get the next month.
int theMonth = ((System.DateTime)periodStartDate).Month+1;
But if the periodstartDate
int theMonth = ((System.DateTime)periodStartDate).AddMonths(1).Month;
If you call AddMonths(1)
then .NET will automatically roll the date into the next year.
periodStartDate.AddMonths(1).Month;
DateTime now = DateTime.Now;
DateTime nextMonth;
if(now.Day > 1)
nextMonth = now.AddDays(-(now.Day - 1)).AddMonths(1);
else
nextMonth = now.AddMonths(1);
Where Now is the Date you want to start ,you could replace with TheStartPeriod
The trick part is to understand the start date could not start in the first day of the current month, so a plain AddMonth
could lead to undesired dates. Build a new DateTime in the day 01 and, then, add the month.
var firstDayNextMonth = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(+1);
BTW, the AddMonths method documentation states:
The AddMonths method calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object. If the resulting day is not a valid day in the resulting month, the last valid day of the resulting month is used. For example, March 31st + 1 month = April 30th, and March 31st - 1 month = February 28 for a non-leap year and February 29 for a leap year.
I think you can get it in this fashion
DateTime dt = new DateTime(2011,12,2);
DateTime dayone = new DateTime(dt.AddMonths(1).Year, dt.AddMonths(1).Month, 1);
Now you have a proper DateTime
object to the first of the next month, do as you please with it
The expression ((System.DateTime)periodStartDate).Month+1
doesn't throw an error if the month is December - it just returns 13. I suspect you're doing this:
var nextMonth = new DateTime(periodStartDate.Year, periodStartDate.Month + 1, 1);
That would throw an error.
Try this instead:
var nextMonth = new DateTime(periodStartDate.Year, periodStartDate.Month, 1)
.AddMonths(1);