I'm wondering how can I calculate what is the week of the month based on the ordinal number of the week of the year. For example I'm dealing with week 33, I should know that's Week 2 in august. I allready calculated months but now I'm dealing with weeks.
I allready have a solution, but it seems dirty to me..
Here's the code:
var data = query.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.CreatedDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(article => new ArticleSimpleObject
{
Week = GetWeekNumberOfMonth(article.FirstOrDefault().CreatedDate.Value),
Amount = article.Sum(x => x.Amount),
Month = article.FirstOrDefault().CreatedDate.Value.Month
});
And here's the method which I used to get week numbers:
private static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
As I wrote guys, this solutions works,
but I personally don't like it, I guess there is more elegant solution, and that's why I posted this question to help to myself and to future readers if some experienced person helps us to solve this :)
Maybe this could be solved based on Calendar class https://learn.microsoft.com/en-us/dotnet/api/system.globalization.calendar?view=netframework-4.8
I've tried some variant but I was not even close to solve it..
Thanks guys
Cheers