Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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.

like image 685
andrewsimon Avatar asked Aug 23 '11 10:08

andrewsimon


3 Answers

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

like image 153
V4Vendetta Avatar answered Oct 09 '22 03:10

V4Vendetta


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);
like image 26
Enigmativity Avatar answered Oct 09 '22 04:10

Enigmativity


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);
like image 41
sympatric greg Avatar answered Oct 09 '22 02:10

sympatric greg