person AJ access_time 3 months ago
Re: C# - Get Current and Last Month Start and End Date
monthEnd
and lastMonthEnd
to:var
monthEnd = monthStart.AddMonths(1).AddSeconds(-1);
var lastMonthEnd = monthStart.AddSeconds(-1);
This will output for example (it's January 2023)monthEnd
= 1/31/2023 11:59:59 PMlastMonthEnd
= 12/31/2022 11:59:59 PM
This 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:
int currMonthOrders = dataSet1.myOrders.AsEnumerable().Where(row => row.Field<DateTime>("yourDateColumn") >= monthStart && row.Field<DateTime>("yourDateColumn") <= monthEnd).Count(); label1.Text = "You have done " +currMonthOrders.ToString("N0")+ " purchases this month";
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.