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;
    }
}
view raw Week.cs This Gist brought to you by GitHub.

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.



1 Comment

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