Skip to content

Instantly share code, notes, and snippets.

@jpswade
Last active January 25, 2020 12:43
Show Gist options
  • Save jpswade/f09f1ba88a2dcaa1538f10c8aea380e6 to your computer and use it in GitHub Desktop.
Save jpswade/f09f1ba88a2dcaa1538f10c8aea380e6 to your computer and use it in GitHub Desktop.
A class to get working days between two dates...
<?php
namespace App\Services;
use DateInterval;
use DatePeriod;
use DateTime;
use Exception;
use Illuminate\Support\Facades\Cache;
class WorkingDays
{
const DISPLAY_DATE_FORMAT = 'D, Y-M-d';
const HOLIDAYS_DATE_FORMAT = 'Y-m-d';
const HOLIDAYS_CACHE_MINUTES = 60 * 24 * 30;
/**
* @var string
*/
private $dateFrom;
/**
* @var string
*/
private $dateTo;
/**
* WorkingDays constructor.
* @param string $dateFrom
* @param string $dateTo
*/
public function __construct($dateFrom, $dateTo)
{
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
}
/**
* @return DateTime[]
* @throws Exception
*/
public function __toArray()
{
$holidays = $this->getHolidays();
$startDate = new DateTime($this->dateFrom);
$endDate = new DateTime($this->dateTo);
$interval = new DateInterval('P1D');
$dateRange = new DatePeriod($startDate, $interval, $endDate);
$results = [];
/** @var DateTime $date */
foreach ($dateRange as $date) {
if ($date->format('N') < 6 &&
!in_array($date->format(self::HOLIDAYS_DATE_FORMAT), $holidays)) {
$results[] = $date;
}
}
return $results;
}
/**
* @return array
*/
protected function getHolidays()
{
$url = 'https://www.gov.uk/bank-holidays.json';
$holidaysData = Cache::get($url);
if (!$holidaysData) {
$holidaysData = file_get_contents($url);
Cache::put($url, $holidaysData, self::HOLIDAYS_CACHE_MINUTES);
}
$holidaysArray = json_decode($holidaysData, true);
$holidays = [];
foreach ($holidaysArray['england-and-wales']['events'] as $event) {
$holidays[] = $event['date'];
}
return $holidays;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment