Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate DateTime Weeks into Rows

Tags:

c#

asp.net

I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:

var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {

This works fine, however, some month will only have 5 weeks and in some rare cases, 4.

How can I calculate the number of rows that will be required for a particular month?

This is an example of what I am creating:

enter image description here

As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.

Image found on google


This is an example of what I am creating:

enter image description here

As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.

Image found on google

like image 223
GateKiller Avatar asked Aug 13 '08 13:08

GateKiller


Video Answer


1 Answers

Here is the method that does it:

public int GetWeekRows(int year, int month)
{
    DateTime firstDayOfMonth = new DateTime(year, month, 1);
    DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
    System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
    int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    return lastWeek - firstWeek + 1;
}

You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory.

like image 161
Serhat Ozgel Avatar answered Sep 19 '22 03:09

Serhat Ozgel