proseidon
proseidon

Reputation: 2305

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

Upvotes: 11

Views: 13379

Answers (5)

Joe Lutz
Joe Lutz

Reputation: 31

Try this simple one-liner:

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

Upvotes: 3

Sorceri
Sorceri

Reputation: 8053

lots of examples...pick your posion ;)

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()));

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21897

Try this:

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

Upvotes: 23

Felipe Oriani
Felipe Oriani

Reputation: 38638

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 

Upvotes: 2

Cory Nelson
Cory Nelson

Reputation: 30031

This won't ever cause out-of-range errors, and will preserve the DateTime's Kind.

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

Upvotes: 7

Related Questions