Alex Rivera | Logout

How to find the first day of next month,if the current month is december

Asked 2011-08-23T10:33:31.747
37

I'm using the following query to get the next month.

int theMonth = ((System.DateTime)periodStartDate).Month+1;

But if the periodstartDate month id=s december,the above statement throws error.

Edit
Report

2 Answers

13

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);
answered 2013-05-10T12:35:22.883
1

If you call AddMonths(1) then .NET will automatically roll the date into the next year.

periodStartDate.AddMonths(1).Month;
answered 2011-08-23T10:40:07.037

Your Answer