Setting DateTime to the first of next month?

If I have var olddate = DateTime.Parse('05/13/2012');

and I want to get var newdate = (the first of the month after olddate, 06/01/2012 in this case);

What would I encode? I tried to set month + 1, but month has no setter.

+8
c #
source share
5 answers

Try the following:

 olddate = olddate.AddMonths(1); DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1, 0, 0, 0, olddate.Kind); 
+20
source share

This will never cause errors out of range and keep the DateTime View.

 dt = dt.AddMonths(1.0); dt = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind); 
+7
source share

You must correctly determine the month and year, and then set the 1st day. Try the following:

 // define the right month and year of next month. var tempDate = oldDate.AddMonths(1); // define the newDate with the nextmonth and set the day as the first day :) var newDate = new DateTime(tempDate.Year, tempDate.Month, 1); //create 
+2
source share

many examples ... choose your position;)

 var olddate = DateTime.Parse("05/12/2012"); int currentDay = ((DateTime)olddate).Day; //can always replace the while loop and just put a 1 for current day while(currentDay != 1) currentDay--; var newdate = (DateTime.Parse(olddate.AddMonths(1).Month.ToString() + "/" + currentDay.ToString() + "/" + olddate.AddMonths(1).Year.ToString())); 
0
source share

Try this simple single line layer:

 var olddate = DateTime.Parse("05/13/2012"); var newdate = olddate.AddDays(-olddate.Day + 1).AddMonths(1); // newdate == DateTime.Parse("06/01/2012") 
0
source share

All Articles