Reputation: 245
I have a problem with the calendar that I use to get me a smaller number of weeks for certain months For example, this happens to me at Sept 2019, where my number is 5 or in July 2018, which is also 5. How can I fix this? this is my current code:
private DateTime _calendarDate;
int numWeeks = NumberOfWeeks(_calendarDate.Year, _calendarDate.Month);
private int NumberOfWeeks(int year, int month)
{
return NumberOfWeeks(new DateTime(year, month, DateTime.DaysInMonth(year, month)));
}
private int NumberOfWeeks(DateTime date)
{
var beginningOfMonth = new DateTime(date.Year, date.Month, 1);
while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
date = date.AddDays(1);
return (int)Math.Truncate(date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
}
additional information on CultureInfo
The problem is that it always comes back to me one week less, so my calendar doesn't display it properly and then I get the error,
Here's an example for April 2018 where you give me 5 weeks, and then another one is missing and that's why I'm getting the error
can anyone guess how i could solve this problem?
Upvotes: 3
Views: 167
Reputation: 355
Here is a bit more mathematical solution:
int myYear = 2019, myMonth = 12; // the example for December 2019
var firstMonthDay = new DateTime(myYear, myMonth, 1);
int delta = firstMonthDay.DayOfWeek - System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
if (delta < 0)
delta += 7;
int daysInMonth = DateTime.DaysInMonth(myYear, myMonth);
int weekLinesNumber = (int)Math.Ceiling((daysInMonth + delta) / 7F); // the result
We count the delta (could be from 0 to 6), this is the number of days from the first day of the week to the first next month day. Then we count the resulting number of the weeks using Math.Ceiling
function.
In short, we add to the month some delta days at the beginning in order to get new Extra Month block starting from the First Day of a Week (according to the culture). And then we count the total number of the occupied week lines. No need to add +1
when we use Math.Ceiling
function.
Upvotes: 0
Reputation: 454
When you can use System.Globalization.Calendar
you can get the count of weeks in a month by using GetWeekOfYear
for the first and the last day of the month and then calculate the difference (and add 1 to include the first week).
This would change your NumberOfWeeks()
to the following:
private int NumberOfWeeks(DateTime date)
{
Calendar calendar = CultureInfo.CurrentCulture.Calendar;
var firstOfMonth = new DateTime(date.Year, date.Month, 1);
var week1 = calendar.GetWeekOfYear(firstOfMonth, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
var week2 = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
int numberOfWeeks = (week2 - week1) + 1;
return numberOfWeeks;
}
For your example (April 2018) this will give you 6 as a result and for May 2018 it will give you 5.
Upvotes: 1