C# - Get Current and Last Month Start and End Date
This code snippet provides example about calculating current or last month's start and end date using C# in .NET. In time related calculations or data analytics, it is often required.
Code snippet
var today = DateTime.Today;
var monthStart = new DateTime(today.Year, today.Month, 1);
var monthEnd = monthStart.AddMonths(1).AddDays(-1);
var lastMonthStart = monthStart.AddMonths(-1);
var lastMonthEnd = monthStart.AddDays(-1); Console.WriteLine("Current month start date is: {0}, end date is: {1}", monthStart, monthEnd); Console.WriteLine("Last month start date is: {0}, end date is: {1}", lastMonthStart, lastMonthEnd);
You can apply similar approaches to other programming languages.
Thanks for sharing AJ and welcome to Kontext. If you want to be even more accurate, you can also consider milliseconds as there might be possibilities that some purchases will land on the last second.
the best way to avoid this if by using the Month function of sql (you can query using SqlDataAdapter or SqlCommand at your like)
SELECT
* FROM
myOrders WHERE MONTH
(date_column) = 12 AND YEAR
(date_column) = 2022;
This will be more accurate and give you all records of December 2022 no matter the time ;)
monthEnd
andlastMonthEnd
to:This will output for example (it's January 2023)
monthEnd
= 1/31/2023 11:59:59 PMlastMonthEnd
= 12/31/2022 11:59:59 PMThis works in my shop in the case let's say I registered a purchase on 12/31/2022 10:05 AM, the LastMonthEnd will originally output the last day of the month but just at 12/31/2022 12:00:00 AM, so when you look up for records of December 2022 that purchase won't count.
If not expert with queries (like me) we would normally search between two dates with '<=' and '>=' operators and this won't count that purchase unless using the edit above, for example I used LINQ to count my purchases of the current month in a filled DataTable: