Skip to content

Core\Time\Date::compareTo

$date->compareTo(Core\Time\Date $other): int$date->compareTo(
    Core\Time\Date $other,
): int

Compares two dates and tells you which one comes first in the calendar.

The result is -1 when the date is earlier than the other one, 0 when both are the same day, and 1 when it is later.

You can also write <, >, <=, >= and <=> between two dates. They all use compareTo. == is true when both dates are the same day.

Use it to check a date against a limit, for example whether a coupon is still valid on the day of an order. Core\Arr::sort needs a function that compares two values. Give it a function that calls compareTo, and it sorts a list of dates from the earliest to the latest.

Parameters

  • $otherCore\Time\DateThe date to compare against.

Return value

Returns int. -1 when the receiver is earlier than $other, 0 when they are the same day, 1 when it is later.

Examples

Which date comes first

<?nvs
// Shows how to find out which of two dates comes first.
var $start = Core\Time\Date::at(2024, 3, 1);
var $end = Core\Time\Date::at(2024, 3, 15);
// `compareTo` returns -1 for an earlier date, 0 for the same day and 1 for a later date.
// This prints -1, then 0, then 1.
echo $start->compareTo($end), "\n";
echo $start->compareTo(Core\Time\Date::at(2024, 3, 1)), "\n";
echo $end->compareTo($start), "\n";
Output
-1
0
1

Sorting dates

<?nvs
// Shows how to sort a list of dates from the earliest to the latest.
array<Core\Time\Date> $deliveries = [
Core\Time\Date::at(2024, 11, 2),
Core\Time\Date::at(2023, 12, 24),
Core\Time\Date::at(2024, 2, 9),
];
// `Core\Arr::sort` needs a function that compares two values, and `compareTo` is that function.
array<Core\Time\Date> $sorted = Core\Arr::sort($deliveries, {
comparator: fn(Core\Time\Date $a, Core\Time\Date $b): int => $a->compareTo($b),
});
// This prints 2023-12-24, then 2024-02-09, then 2024-11-02.
foreach ($sorted as Core\Time\Date $day) {
echo $day->format('yyyy-MM-dd'), "\n";
}
Output
2023-12-24
2024-02-09
2024-11-02

A coupon that expires

<?nvs
// Shows how to check whether a coupon is still valid on the day of an order.
// The coupon can be used up to and including its last day.
var $lastDay = Core\Time\Date::at(2024, 6, 30);
array<Core\Time\Date> $orders = [
Core\Time\Date::at(2024, 6, 29),
Core\Time\Date::at(2024, 6, 30),
Core\Time\Date::at(2024, 7, 1),
];
// A result of 0 or less means the order is not later than the last day.
// This prints "valid" twice and then "expired".
foreach ($orders as Core\Time\Date $ordered) {
if ($ordered->compareTo($lastDay) <= 0) {
echo $ordered->format('yyyy-MM-dd'), ": valid\n";
} else {
echo $ordered->format('yyyy-MM-dd'), ": expired\n";
}
}
Output
2024-06-29: valid
2024-06-30: valid
2024-07-01: expired