I had a technical test and one of the things I had to do is a program that has an input of two dates, and has to output the months with 5 sundays between these two dates. A string $dates has the two dates in the same line
example: juny 2014 october 2014
I need to use these two dates to do stuff.
In this point, I was thinking to do two separate strings to work with each date, like this:
$arrayDates = split(" ",$dates);
Then:
$firstDate = $dates[0].$dates[1];
$secondDate = $dates[2].$dates[3];
But I see this way of doing things too obvious and not dynamyc. Somebody knows a better or more elegant/apropriate way to do this?
Edit: this is the full code
<?php
date_default_timezone_set('UTC');
//output month with five sundays
foreach(file($argv[1]) as $date){
$totalDays=prepareDateArray($date);
calculateSundays($totalDays,$date);
}
function prepareDateArray(&$date){
$regexPattern = "/([a-z]+ [0-9]{4})/i";
$matchCount = preg_match($regexPattern, $date, $matches);
if($matchCount == 0)return;
$date = preg_replace("# +#",' ',$date);
$date = split(' ',$date);
$totalDays = parseDate($date);
return $totalDays;
}
function parseDate(&$date){
$nIndex = count($date);
if($nIndex%2==0){
//Add first day of the month to first Date
$date[0] = '01-'.$date[0].'-'.$date[1];
//Get lastMonthDay
$lastMonthDay = date('t', strtotime($date[2].'-'.$date[3]));
//Add last day of the month to secondDate
$date[1] = $lastMonthDay.'-'.$date[2].'-'.$date[3];
//Calculates distance between dates in days
$firstDate = strtotime($date[0]);
$secondDate = strtotime($date[1]);
if($firstDate>$secondDate)exit('First date must be earlier than second date');
$datediff = $secondDate - $firstDate;
unset($date[2],$date[3]);
return $datediff/(60*60*24);
}else{
exit('Insert valid input');
}
}
function calculateSundays($totalDays,$tempDate){
$sundays=0;
$output=0;
for($day=1;$day<=$totalDays;$day++)
{
$dayOfWeek = date('w', strtotime($tempDate[0].' + '.$day.' days'));
if($dayOfWeek == 0)$sundays++;
if($sundays == 5){
$output++;
$sundays = 0;
}
}
if($output == 0)print("Wrong date \n");
else print($output."\n");
}
?>