# PHP Job Interview Task: Day of Week Calculation

Share:

Not so long ago, I was given a job interview task. I was to write a function which deduces the day of the standard 7-day week of an imaginary calendar, provided I know how often leap years happen, if at all, how many months their year has, and how many days each month has.

This is a fairly common introductory job-interview task, and in this article I'll be solving and explaining the math behind it. I'm no Rainman so feel free to throw simplifications and corrections at me – I'm sure my way is one of the needlessly complex ones. This article will be presenting two ways of approaching the problem – one that allows you to mentally do this on-the-fly (impress your friends, I guess?), and one that is more computer friendly (fewer lines of code, larger numbers).

The definition of the calendar I was given went as follows:

- each year has 13 months
- each even month has 21 days, and each odd month has 22
- the 13th month lacks a day every leap year
- a leap year is any year divisible by 5
- each week has 7 days: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

The task went as follows:

Given that the first day of the year 1900 was Monday, write a function that will print the day of the week for a given date. Example, for input {day: 17, month: 11, year: 2013} the output is "Saturday".

Throughout the rest of the article, I will be using the following date format: dd.mm.yyyy, because it's what makes sense.

## Preparation

Before starting out on any brainy venture, it's important to have a proper environment set up in order to avoid wasting time on things that could have been prepared in advance. I always recommend you venture into coding job interview tasks with a revved up development environment, ready to test your code at a moment's notice.

Create a new folder containing two subfolders: `classes`

, and `public`

. Yes, this is a throwaway task that can be solved in a simple procedural function, but I like to be thorough. You'll see why.

In the `classes`

subfolder, create an empty PHP class called `CalendarCalc.php`

. In the `public`

subfolder, create a file called `index.php`

with the following content:

```
<?php
require_once '../classes/CalendarCalc.php';
echo "Hello";
```

If you can open this in your browser and "Hello" is displayed, you're ready to get started.

## CalendarCalc initialization

To make things easier to verify and visualize, I've created a demo method which prints out the entire calendar from 1.1.1900. to 22.13.2013. This will allow us to easily check if our calculation function works. First, though, initialize the class like so:

```
<?php
class CalendarCalc {
/** @var array */
protected $aDays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
/** @var int Cached number of days in a week, to avoid recounts. This way, we can alter the week array at will */
protected $iNumDays;
/** @var int Array index of starting day (1.1.1900.), i.e. Monday = 1*/
protected $iStartDayIndex;
/** @var int */
protected $startYear = 1900;
/** @var int */
protected $leapInterval = 5;
/** @var array Array gets populated on instantiation with date params. This is to make params accessible to every alternative calculation method. */
protected $aInput = array();
public function __construct($day, $month, $year) {
$this->iNumDays = count($this->aDays);
$this->iStartDayIndex = array_search('Monday', $this->aDays);
$this->aInput = array('d' => $day, 'm' => $month, 'y' => $year);
}
public function demo() {
}
}
```

Let's explain the protected properties.

`$aDays`

is an array of days. Defining it made sure each day of the week has a numeric index assigned to it – something of utmost importance when determining the day of the week later on. We cache its length with the `$iNumDays`

property. This allows us to expand the days array later on, if we so choose – another task might ask for the same calculation, but might mention that the week has more or less than 7 days.

`$iStartDayIndex`

is the index of Monday (in this case), because the start day (1.1.1900.) is defined as Monday in the task description. When we have the index of the start day, we can use it in tandem with a calculated offset to get the real day of the week. You'll understand what I mean in a bit.

`$aInput`

is an array to hold the input values. When we instantiate the CalendarCalc, we pass in the date values for which we want to know the day of the week. This property stores those values, making them available for every alternative calc method we think up, thus making sure we don't need to forward them along, or even worse, repeat them in another function call. The logic of `$aInput`

, `$iStartDayIndex`

and `$iNumDays`

is in the `__construct`

method.

The other properties are self-explanatory.

Now, populate the `demo()`

method with the following content:

```
public function demo() {
$demoYear = $this->startYear;
$totalDays = 0;
while ($demoYear < 2014) {
echo "<h2>$demoYear</h2><table>";
$demoMonth = 1;
while ($demoMonth < 14) {
echo "<tr><td colspan='7'><b>Month $demoMonth</b></td></tr>";
echo "<tr><td>Monday</td><td>Tuesday</td><td>Wednesday</td><td>Thursday</td><td>Friday</td><td>Saturday</td><td>Sunday</td></tr>";
$dayCount = ($demoMonth % 2 == 1) ? 22 : 21;
$dayCount = ($demoMonth == 13 && $demoYear % 5 == 0) ? 21 : $dayCount;
$demoDay = 1;
echo "<tr>";
while ($demoDay <= $dayCount) {
$index = ++$totalDays % 7;
if ($demoDay == 1) {
for ($i = 0; $i < $index-1; $i++) {
echo "<td></td>";
}
if ($index == 0 || $index == 7) {
$i = 6;
while ($i--) {
echo "<td></td>";
}
}
}
echo "<td>$demoDay</td>";
if ($index == 0) {
echo "</tr><tr>";
}
$demoDay++;
}
echo "</tr>";
$demoMonth++;
}
echo "</table><hr />";
$demoYear++;
}
}
```

Don't bother trying to understand this method – it's entirely unimportant. It's only there to help us verify our work, and is in fact partially based on the second solution we'll be presenting in this article.

Change the contents of the index.php file to:

```
<?php
require_once '../classes/CalendarCalc.php';
$cc = new CalendarCalc(17, 11, 2013);
$cc->demo();
```

…and open it in the browser. You should see a calendar output not unlike the one in the image below:

We now have a way to check the results against the truth (notice that the date 17.11.2013. is indeed Saturday).

## The mental way

The mental way to do this calculation is actually quite simple. First, we need the number of leap years between the base date, and our given date. 1900 is divisible by 5 and is itself a leap year. The number of leaps is thus the difference in years between the input date and the base date, divided by 5, rounded down (only fully elapsed years count, naturally), plus one for 1900. Create a new method in `CalendarCalc`

called `calcFuture`

and give it this content:

`$iLeaps = floor(($this->aInput['y'] - $this->startYear) / $this->leapInterval + 1);`

We were also told that each even month has 21 days, and each odd month has 22:

1 => 22

2 => 21

3 => 22

4 => 21

5 => 22

6 => 21

7 => 22

8 => 21

9 => 22

10 => 21

11 => 22

12 => 21

13 => 22 (or 21 on leap years)

The total number of days in their year is, thus, 280, or 279 on leap years. If we take the modulo of 280 % 7, we get 0, because 280 is divisible by 7. On leap years, the modulo is 6.

This means that every year of that calendar begins on the same day, except on leap years, when it begins on the day that precedes the previous year's first day. Thus, if 1.1.1900. was Monday:

- 1.1.1901. is Monday
- 1.1.1902. is Sunday
- 1.1.1903. is Sunday
- 1.1.1904. is Sunday
- 1.1.1905. is Saturday
- 1.1.1906. is Saturday
- etc…

According to this, we can calculate the number of day moves until our input year. Seeing as we know we have 23 leaps until the input date (2013), we moved back a day 23 times. The modulo of 23 % 7 is 2, meaning we came full circle 3 times and then two more days (this is the offset) – 1.1.2013. was Saturday. Check on the demo calendar and see for yourself.

Let's put this into code. After the "leaps" line above, add the following:

```
$iOffsetFromCurrent = $iLeaps % $this->iNumDays;
$iNewIndex = $this->iStartDayIndex - $iOffsetFromCurrent;
if ($iNewIndex < 0) {
$iFirstDayInputYearIndex = $this->iStartDayIndex + $this->iNumDays - $iOffsetFromCurrent;
} else {
$iFirstDayInputYearIndex = $iNewIndex;
}
```

First, we calculate the offset. Then, we calculate the new index of the days array, which varies depending on whether or not the new index is positive. This gives us the day of the week on which our input year starts.

We also know that each month X with 21 days makes the next month Y start on the same day as month X did, because 21 % 7 = 0. During odd months, however, the starting day moves ahead by one (22 % 7 = 1). So if Month 1 started with Saturday, Month 2 starts with Sunday, Month 3 with Sunday, Month 4 with Monday, and so on. We conclude that every odd month that passed since the start of the year until our input date's month has advanced the day index by 1. We're in month 11, so there were 5 odd months. The new offset is +5 or in our case, the 11th month of 2013 begins on Thursday. Let's put it into code immediately under the previous lines.

```
$iOddMonthsPassed = floor($this->aInput['m'] / 2);
$iFirstDayInputMonthIndex = ($iFirstDayInputYearIndex + $iOddMonthsPassed) % $this->iNumDays;
```

All that's left now is to see how far removed from the beginning of the month our input date's day is.

```
$iTargetIndex = ($iFirstDayInputMonthIndex + $this->aInput['d']-1) % $this->iNumDays;
return $this->aDays[$iTargetIndex];
```

We add the day number minus one (because the day hasn't passed yet!) and modulo it with 7, the number of days. The number we get is our target index, reliably giving us Saturday.

From the top now, the whole `calcFuture`

method of `CalendarCalc`

goes like this:

```
/**
* A more "mental" way of calculating the day of the week
* @return mixed
*/
public function calcFuture() {
$iLeaps = floor(($this->aInput['y'] - $this->startYear) / $this->leapInterval + 1);
$iOffsetFromCurrent = $iLeaps % $this->iNumDays;
$iNewIndex = $this->iStartDayIndex - $iOffsetFromCurrent;
if ($iNewIndex < 0) {
$iFirstDayInputYearIndex = $this->iStartDayIndex + $this->iNumDays - $iOffsetFromCurrent;
} else {
$iFirstDayInputYearIndex = $iNewIndex;
}
$iOddMonthsPassed = floor($this->aInput['m'] / 2);
$iFirstDayInputMonthIndex = ($iFirstDayInputYearIndex + $iOddMonthsPassed) % $this->iNumDays;
$iTargetIndex = ($iFirstDayInputMonthIndex + $this->aInput['d']-1) % $this->iNumDays;
return $this->aDays[$iTargetIndex];
}
```

## The machine-friendly way

A perhaps simpler approach is just calculating the number of days that have elapsed since the base date, modulo that by 7 and get the offset that way. There's not many people who can calculate numbers of this magnitude on the fly, though, and that's why it's more machine-friendly.

Again, we need leaps:

```
public function calcFuture2() {
$iTotalDays = 0;
$iLeaps = floor(($this->aInput['y'] - $this->startYear) / $this->leapInterval + 1);
}
```

Then, take years into account first. That's 280 times number of elapsed years, minus number of leaps to account for lost days, plus one because the current year is still ongoing.

` $iTotalDays = (280 * ($this->aInput['y'] - $this->startYear)) - $iLeaps + 1;`

Then, we add in the days by summing up all the elapsed months.

` $iTotalDays += floor($this->aInput['m'] / 2) * 21 + floor($this->aInput['m'] / 2) * 22;`

Finally, we add the days of the input date, again minus one because the current day hasn't passed yet:

```
$iTotalDays += $this->aInput['d'] - 1;
return $this->aDays[$iTotalDays % $this->iNumDays];
```

Dead simple, no?

## Conclusion

To see a live example of this calculation, please check here. You can browse the containing directory at that URL to see the files, or you can download the complete source code of that demo site, along with the final `CalendarCalc`

class, from Github. The repo/demo has slightly more code than presented in this article – some html5boilerplate was used to make it more organized and to enable ajax requests to check the dates as you enter them, so you don't need to reload the screen and regenerate the calendar every time you check for a date.

If you have alternative solutions or suggestions for improvement, please leave them in the comments below – like I said I'm no math wiz and I welcome the opportunity to learn more. For example, one should take corner cases into account – edge dates, or dates in the past require more modifications to the original algorithm. I'll leave that up to you. Feel free to submit a pull request and you'll get a shout out in the article!

Hope you enjoyed this and learned something new! Good luck in your interviews!

Bruno is a blockchain developer and technical educator at the Web3 Foundation, the foundation that's building the next generation of the free people's internet. He runs two newsletters you should subscribe to if you're interested in Web3.0: Dot Leap covers ecosystem and tech development of Web3, and NFT Review covers the evolution of the non-fungible token (digital collectibles) ecosystem inside this emerging new web. His current passion project is RMRK.app, the most advanced NFT system in the world, which allows NFTs to own other NFTs, NFTs to react to emotion, NFTs to be governed democratically, and NFTs to be multiple things at once.