Mental Floss: The Month on the Calendar
So we’ve seen what the Calendar looks like, and how it’s building it’s Months, but what goes into building a Month?
So building a Month is all about one thing: building it’s weeks. The only other thing I need from a month is the ability to get it’s name (i.e. January, February, etc.). My implementation of this looks something like this:
public class Month{ private DateTime FirstDayOfMonth { get; set; } private IList<Week> Weeks { get; set; }
public Month(int monthValue) { FirstDayOfMonth = new DateTime(DateTime.Now.Year, monthValue, 1); Weeks = new List<Week>();
BuildMonth(); }
private void BuildMonth() { var startDay = Calendar.GetStartDay();
var week = new Week();
var day = FirstDayOfMonth; do { if (WeekHasEnded(day, startDay) && WeekIsNotEmpty(week)) { Weeks.Add(week); week = new Week(); }
week.Add(day); day = GetNextDay(day);
} while (day.Month == FirstDayOfMonth.Month);
Weeks.Add(week); }
private bool WeekIsNotEmpty(Week week) { return week.GetDays().Count() > 0; }
private bool WeekHasEnded(DateTime day, DayOfWeek startDay) { return day.DayOfWeek == startDay; }
private DateTime GetNextDay(DateTime day) { return day.AddDays(1); }
public DayOfWeek GetFirstDayOfMonth() { return FirstDayOfMonth.DayOfWeek; }
public IList<Week> GetWeeks() { return Weeks; } public string GetMonthName() { return string.Format("{0:MMMM}", FirstDayOfMonth); }}
This entry was posted on Monday, October 17th, 2011 at 8:00 am and is filed under Programming.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

[...] we’ve gone through how the month is modeled, we need to see how weeks are being [...]