C#: Find Previous Month's First and Last Day

Here’s a simple query that gives you the first and last day of the previous month.

static void Main(string[] args)
var yr = DateTime.Today.Year;
var mth = DateTime.Today.Month;
var firstDay = new DateTime(yr, mth, 1).AddMonths(-1);
var lastDay = new DateTime(yr, mth, 1).AddDays(-1);
Console.WriteLine("First day Previous Month: {0}", firstDay);
Console.WriteLine("Last day Previous Month: {0}", lastDay);

C# Previous Month Dates
You can also use the following method to get the last day of any month. Assuming you want the last day of the current month

var lastDayMonth = DateTime.DaysInMonth(dt.Year, dt.Month);

If you want to do the same in SQL Server, check my post SQL Server: First Day of Previous Month and Find First and Last Day Of Each Month

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: