As opposed to testing the explicit day of the week string or number, you can also test using the relative date this weekday
of the supplied date.
A direct comparison between the values is not possible without a workaround, as the use of weekday
resets the time of the supplied date to 00:00:00.0000
.
DateTimeInterface
objects
$date->setTime(0, 0, 0) != $date->modify('this weekday');
DateTimeInterface
Method
A simple method to implement to ensure the supplied date object is not changed.
function isWeekend(DateTimeInterface $date): bool
{
if ($date instanceof DateTime) {
$date = DateTimeImmutable::createFromMutable($date);
}
return $date->setTime(0,0,0) != $date->modify('this weekday');
}
isWeekend(new DateTimeImmutable('Sunday')); //true
strtotime
method
With strtotime
you can compare with the date('Yz')
format. If the Yz
value changes between the supplied date and this weekday
, the supplied date is not a weekday.
function isWeekend(string $date): bool
{
return date('Yz', strtotime($dateValue)) != date('Yz', strtotime($dateValue . ' this weekday'));
}
isWeekend('Sunday'); //true
Example
https://3v4l.org/TSAVi
$sunday = new DateTimeImmutable('Sunday');
foreach (new DatePeriod($sunday, new DateInterval('P1D'), 6) as $date) {
echo $date->format('D') . ' is' . (isWeekend($date) ? '' : ' not') . ' a weekend';
}
Result
Sun is a weekend
Mon is not a weekend
Tue is not a weekend
Wed is not a weekend
Thu is not a weekend
Fri is not a weekend
Sat is a weekend