arrow_back C# - Get Current and Last Month Start and End Date

3 months ago link more_vert
Raymond Raymond
articleArticles 549
codeCode 3
imageDiagrams 49
descriptionNotebooks 0
chat_bubble_outlineThreads 8
commentComments 268
loyaltyKontext Points 6058
account_circleProfile
#1789 Re: C# - Get Current and Last Month Start and End Date

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.

format_quote

person AJ access_time 3 months ago
Re: C# - Get Current and Last Month Start and End Date

Thank you Raymond, it was very helpful for me! To anyone that needs the very last instance of the end date, just edit 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 PM
lastMonthEnd = 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";
recommendMore from Kontext