Get week from selected monthcalendar-date
-
24-06-2021 - |
Question
I need a solution to calculate the week from the selected date. (in monthcalendar)
I tried:
DateTime dt1 = new DateTime(monthCalendar1.SelectionStart.Year,
monthCalendar1.SelectionStart.Month,
monthCalendar1.SelectionStart.Day);
DateTime dt2 = new DateTime(monthCalendar1.SelectionStart.Year,
1,
1);
System.TimeSpan varTime = dt1 - dt2;
int weeks = (varTime.Days / 7) + 1;
But start and enddays of a weeks are not correct and in some years I got 53 weeks?
what is the best way to solve this?
Solution
public int WeekNumber(DateTime date)
{
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(date,
CalendarWeekRule.FirstFourDayWeek,
DayOfWeek.Monday);
return weekNum;
}
Remember to correct the CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday to your current culture, the one use here is for danish/denmark
OTHER TIPS
Try the GetWeekOfYear function of calendar. look here and scroll down for full example: http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow