10

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 code? I tried to set the month+1 but month has no setter.

4

5 回答 5

23

尝试这个:

olddate = olddate.AddMonths(1);
DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1, 
    0, 0, 0, olddate.Kind);
于 2012-12-06T21:47:54.057 回答
7

这永远不会导致超出范围的错误,并且会保留DateTime's Kind.

dt = dt.AddMonths(1.0);
dt = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind);
于 2012-12-06T21:49:48.667 回答
2

You have to define the Month and Year rightly, and after set the 1ª day. Try this:

// 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 
于 2012-12-06T21:51:31.340 回答
2

试试这个简单的单行:

var olddate = DateTime.Parse("05/13/2012");
var newdate = olddate.AddDays(-olddate.Day + 1).AddMonths(1);
// newdate == DateTime.Parse("06/01/2012")
于 2016-10-14T16:38:16.793 回答
0

很多例子......选择你的位置;)

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()));
于 2012-12-06T21:59:03.457 回答