Find the Last Day of the Previous Month using C# and VB.NET

A couple of days ago, I had written a post to Find the First and Last Day of the Current Quarter using C#/VB.NET. A user commented asking how to find the last day of the previous month. Here’s how it can be done:


DateTime dt = DateTime.Now;
DateTime lstDay = new DateTime(dt.Year, dt.Month, 1);
lstDay = lstDay.AddDays(-1);
Console.WriteLine("Month: {0}, LastDate: {1}",lstDay.Month, lstDay.Day);


Dim dt As DateTime = DateTime.Now
Dim lstDay As New DateTime(dt.Year, dt.Month, 1)
lstDay = lstDay.AddDays(-1)
Console.WriteLine("Month: {0}, LastDate: {1}",lstDay.Month, lstDay.Day)



The current month is November, so the last day of the previous month (October) is 31.

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: