Code to get Week in a month:
public static int GetWeekInMonth(DateTime date)
{
DateTime tempdate = date.AddDays(-date.Day + 1);
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNumStart = ciCurr.Calendar.GetWeekOfYear(tempdate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int weekNum = ciCurr.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum - weekNumStart + 1;
}
{
DateTime tempdate = date.AddDays(-date.Day + 1);
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNumStart = ciCurr.Calendar.GetWeekOfYear(tempdate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int weekNum = ciCurr.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum - weekNumStart + 1;
}
Code to get number of Weeks in a month:
public static int Weeks(int year, int month)
{
DayOfWeek wkstart = DayOfWeek.Monday;
DateTime first = new DateTime(year, month, 1);
int firstwkday = (int)first.DayOfWeek;
int otherwkday = (int)wkstart;
int offset = ((otherwkday + 7) - firstwkday) % 7;
double weeks = (double)(DateTime.DaysInMonth(year, month) - offset) / 7d;
return (int)Math.Ceiling(weeks);
}
{
DayOfWeek wkstart = DayOfWeek.Monday;
DateTime first = new DateTime(year, month, 1);
int firstwkday = (int)first.DayOfWeek;
int otherwkday = (int)wkstart;
int offset = ((otherwkday + 7) - firstwkday) % 7;
double weeks = (double)(DateTime.DaysInMonth(year, month) - offset) / 7d;
return (int)Math.Ceiling(weeks);
}
Thanks for your solution. This was very helpful.
ReplyDelete