Skip to content

Instantly share code, notes, and snippets.

@m4tthumphrey
Last active December 19, 2015 08:59
Show Gist options
  • Save m4tthumphrey/5930240 to your computer and use it in GitHub Desktop.
Save m4tthumphrey/5930240 to your computer and use it in GitHub Desktop.
<?php
date_default_timezone_set('Europe/London');
$dayInterval = new DateInterval('P1D');
$startDate = new DateTime('2013-07-01');
$duration = null;
if (isset($_GET['duration'])) {
$duration = $_GET['duration'];
$days = 1;
$endDate = clone $startDate;
if (!(preg_match('/^(\d+) (min(ute)?s?)$/i', $duration, $match) && preg_match('/^(\d+) (hours?)$/i', $duration, $match))) {
if ($duration == 'half day') {
$days = 1;
} elseif (preg_match('/^(\d+) (weeks?)$/i', $duration, $match)) {
$days = intval(5 * $match[1]);
} elseif (preg_match('/^(\d+) (days?)$/i', $duration, $match)) {
$days = $match[1];
} elseif (preg_match('/^(\d+) (months?)$/i', $duration, $match)) {
$days = intval(25 * $match[1]);
}
if ($days > 1) {
$endDate->modify(sprintf('%d weekdays', $days - 1));
}
}
} else {
$endDate = new DateTime($_GET['endDate']);
if ($endDate->format('N') == 6) {
$endDate->modify('1 weekdays');
} elseif ($endDate->format('N') == 7) {
$endDate->modify('2 weekdays');
}
}
$days = 0;
foreach(new DatePeriod($startDate, $dayInterval, $endDate->add($dayInterval)) as $day) {
/* 'N' number days 1 (mon) to 7 (sun) */
if ($day->format('N') < 6) {
$days++;
echo sprintf('Day %d: %s (%d)', $days, $day->format('l jS'), $day->format('N')).'<br>';
}
}
if ($days == 1) {
$duration = '1 day';
} elseif ($days < 5) {
$duration = sprintf('%d days', $days);
} elseif ($days < 25) {
$weeks = intval($days / 5);
$mod = $days % 5;
if ($mod > 0) {
$duration = sprintf('%d weeks, %d days', $weeks, $mod);
} else {
$duration = sprintf('%d weeks', $weeks);
}
} else {
$months = intval($days / 25);
$weeksMod = $days % 25;
$weeks = intval($weeksMod / 5);
$daysMod = $weeksMod % 5;
$daysValue = intval($daysMod);
if ($daysMod > 0) {
$duration = sprintf('%d months, %d weeks, %d days', $months, $weeks, $daysValue);
} elseif ($weeksMod > 0) {
$duration = sprintf('%d months, %d weeks', $months, $weeks);
} else {
$duration = sprintf('%d months', $months);
}
}
$endDate->sub($dayInterval);
printf("Start date: %s<br>", $startDate->format('jS F'));
printf("End date: %s<br>", $endDate->format('jS F'));
printf("Days: %d<br>", $days);
printf("Duration: %s<br>", $duration);
@m4tthumphrey
Copy link
Author

Not working properly for 24 days.... but is for 23 and 25....... WTF

@m4tthumphrey
Copy link
Author

Looks like it's sorted....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment