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

No comments:

Post a Comment