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);
Console.ReadLine();
}

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




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: