Thursday, August 7, 2008

First Day of Next Month in VB.Net

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.

15 comments:

BullJustin said...

This is so elegantly simple. Thank you, thank you, thank you.

Stephen Wrighton said...

Glad you liked it.

Anonymous said...

Then to get the last day of the month, I just -1 day:

Now.AddDays((Now.Day - 1) * -1).AddMonths(1).AddDays(-1)

Could not have come up with something so pretty without the inital hard work of the author.

Stephen Wrighton said...

Exactly!

Anonymous said...

nice eureka moment.. thanks

garystafford said...

Thanks! Just what I was looking for.

Anonymous said...

Very impressive - first rate!

Anonymous said...

Damn that's some nice code :D

Anonymous said...

brilliant

Anonymous said...

Wow this is fantastic

Ryan Brooks said...

Very nice! I took this to the next level and made an extension method like so:

public static DateTime GetFirstDayOfMonth(this DateTime date)
{
return date.AddDays((date.Day - 1) * -1).AddMonths(1);
}

Stephen Wrighton said...

@Ryan - That's a great idea to do with this. Can honestly say "wish I had thought of that." :)

..::MackiavHell::.. said...

Man you're a genius!

Praveen said...

Excellent. Thanks man for making human life easier :))

Anonymous said...

Very simple - great snippet!

Blog Widget by LinkWithin