Mental Floss: Weeks on the Calendar
Now we’ve gone through how the month is modeled, we need to see how weeks are being built.
When you first look at the month implementation, you might think that adding days to weeks is a simple matter of adding DateTime’s, but what’s happening behind the scenes is just a little bit more complicated. Why? Well, we need to track what events belong to what days, so in order to do that we can’t just use a simple DateTime, we need something just a little bit more complicated.
My Week looks like this:
public class Week{ public Week() { Days = new List<Day>(); }
protected IList<Day> Days { get; set; }
public IEnumerable<Day> GetDays() { return Days; }
public void Add(DateTime day) { if (!Days.Where(x => x.Date == day.Date).Any()) Days.Add(new Day { Date = day }); }
public bool IsMissingDays() { return Days.OrderBy(x => x.Date) .First().Date.DayOfWeek != Calendar.GetStartDay(); }
public bool IsMissingTrailingDays() { return Days.OrderBy(x => x.Date) .First().Date.DayOfWeek != Calendar.GetLastDay(); }
public int GetMissingNumberOfDays() { var missingDays = 0;
var day = Days.OrderBy(x => x.Date).First().Date; do { day = day.AddDays(-1); missingDays++; } while (day.DayOfWeek != Calendar.GetStartDay());
return missingDays; }
public int GetMissingNumberOfTrailingDays() { var missingDays = 0;
var day = Days.OrderBy(x => x.Date).Last().Date;
do { day = day.AddDays(1); missingDays++; } while (day.DayOfWeek != Calendar.GetLastDay());
return missingDays; }}When adding days to the week, I accept a DateTime and then build a list of Days into the Week. Later on, the calendar will add Events to these Days.
This entry was posted on Wednesday, October 19th, 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.

[...] as I build the week up, I’m adding Days onto it, but what do they look [...]