Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a DateTime to the first of the next month?

Tags:

c#

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.

like image 710
proseidon Avatar asked Dec 06 '12 21:12

proseidon


3 Answers

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")
like image 191
Joe Lutz Avatar answered Nov 10 '22 04:11

Joe Lutz


Try this:

olddate = olddate.AddMonths(1);
DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1, 
    0, 0, 0, olddate.Kind);
like image 25
Dave Zych Avatar answered Nov 10 '22 03:11

Dave Zych


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);
like image 27
Cory Nelson Avatar answered Nov 10 '22 05:11

Cory Nelson