Skip to content

Instantly share code, notes, and snippets.

@mihaeu
Last active January 2, 2016 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mihaeu/b71c6f80cc9fb9a90b24 to your computer and use it in GitHub Desktop.
Save mihaeu/b71c6f80cc9fb9a90b24 to your computer and use it in GitHub Desktop.
Bruno Skvorc posted his solution to a typical job interview question on sitepoint. This is my attempt after 15min on paper and about 5mins of coding, commenting and (typo) debugging. PHP Job Interview Task: Day of Week Calculation http://www.sitepoint.com/php-job-interview-task-day-week-calculation/
<?php
class DateUtils
{
public $offsetYear = 1900;
public $daysInEvenMonth = 21;
public $daysInOddMonth = 22;
public $monthsInYear = 13;
public $leapYearInterval = 5;
public $daysInWeek = 7;
public $weekDays = array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
/**
* Prints the day of the week.
*
* Calculates the number of days since a known offset date
* in order to determin the day of the week.
*
* @param int $year
* @param int $month
* @param int $day
* @return string
*/
public function dayOfTheWeek($year, $month, $day)
{
$yearsSinceOffsetYear = abs($this->offsetYear - $year);
$leapYearsSinceOffsetYear = ceil($yearsSinceOffsetYear / $this->leapYearInterval);
$oddMonthsThisYear = ceil(($month - 1) / 2);
$evenMonthsThisYear = floor(($month - 1) / 2);
$daysInEvenYear = ceil($this->monthsInYear / 2) * $this->daysInOddMonth
+ floor($this->monthsInYear / 2) * $this->daysInEvenMonth;
$daysSinceOffsetYear =
// how many days have passed in the full years
$yearsSinceOffsetYear * $daysInEvenYear - $leapYearsSinceOffsetYear
// how many days have passed in the full months this year
+ $oddMonthsThisYear * $this->daysInOddMonth + $evenMonthsThisYear * $this->daysInEvenMonth
// days this month
+ $day;
$dayOfTheWeekIndex = $daysSinceOffsetYear % $this->daysInWeek;
return $this->weekDays[$dayOfTheWeekIndex];
}
}
$dateUtils = new DateUtils();
printf(
"Day Of The Week on 1900-01-01: %s\n".
"Day Of The Week on 2013-11-17: %s\n",
$dateUtils->dayOfTheWeek(1900, 1, 1),
$dateUtils->dayOfTheWeek(2013, 11, 17)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment