A Programmer's Dream

First Day of Next Month in VB.Net

Posted by Stephen Wrighton on 08 Aug 2008

This is not exactly that hard of a thing, it's just something that I've found myself doing quite a bit in one of my current projects, and I thought of this nice, easy way to do it which I don't want to lose.

Previously to do this, I'd add a month to the current date, use that date object to get the month as integer, build the new date as a string, and then cast said string to a DateTime object.

That's a lot of steps for what should fundamentally be a simple exercise.

Well, it is; provided you don't do it how I was. Check out this snippet of code:
Now.AddDays((Now.Day - 1) * -1).AddMonths(1)
Beautiful huh? What's happening here is that I'm using the NOW function to return a date, I am then subtracting the current day-1 from that date object. What that works out to is as follows: if today's the 15th, then by plugging into the AddDays function 15-1*-1 I'm literally subtracting 14 days from the 15th, which leaves us with the 1st. Pretty huh?

Once I got to the first of the current month, I then add a month to that date, which will return the first of the next month.

Tweet me @kidananubix if you like this post.