Finding the current season using C#

Recently someone challenged me to write a server-side method for finding the current season and changing a style sheet accordingly.

The first step is deciding how to differentiate the seasons. I figured to use the day of the year so that astronomically Spring begins on March 21st, the 80th day of the year. Summer begins on the 172nd day, Autumn, the 266th and Winter the 355th. Of course, on a leap year add one day to each, 81, 173, 267 and 356.

Now to find the day of the year use the DayOfYear property. Also, use the IsLeapYear property to take a day away on leap year if the current day is after February 28th (the 59th day of the year). This is easily done by converting the bool IsLeapYear to an Int32 giving a 0 during non-leap years and 1 during leap year.
int doy = DateTime.Now.DayOfYear - Convert.ToInt32((DateTime.IsLeapYear(DateTime.Now.Year)) && DateTime.Now.DayOfYear > 59);

Then find the current season using a few nested ternary operators (I like ternary operators)
string currentSeason = String.Format("{0}.css",((doy < 80 || doy >= 355) ? "winter" : ((doy >= 80 && doy < 172) ? "spring" : ((doy >= 172 && doy < 266) ? "summer" : "fall"))));

I use this in the head of my MasterPage:
<link rel="Stylesheet" runat="server" id="seasonSheet" type="text/css" />

So all I have to do to add the correct style sheet for the current season is this:
seasonSheet.Attributes.Add("href",currentSeason);

Now a stylesheet named spring.css, summer.css, fall.css or winter.css will be added to your rendered MasterPage.

I hope you’ve found this helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *