Skip to content

Core\Time\TimeOfDay::plus

Moves a time of day forward by a number of hours, minutes, seconds or smaller units, and returns the new time.

The original time does not change. A TimeOfDay has no date, so the result wraps around at midnight: 23:30 plus one hour is 00:30. A negative count moves the time back.

The unit must be Unit::Hour or smaller. Unit::Day and the larger units throw a LogicError, because a time of day has no days to move. A count too large for its unit throws a RuntimeError. To move across days, use a DateTime instead.

Parameters

  • $countintHow many steps. A negative count moves the time back.
  • $unitCore\UnitUnit::Hour or a smaller unit.

Return value

Returns Core\Time\TimeOfDay. A new TimeOfDay. The original does not change.

Errors

  • LogicError$unit is Unit::Day or larger. A time of day has no days to move.
  • RuntimeError$count is too large for $unit.

Examples

When a meeting ends

<?nvs
// Shows how to get the time that is a number of minutes after another time.
Core\Time\TimeOfDay $start = Core\Time\TimeOfDay::at(10, 30);
// This prints 11:15.
echo $start->plus(45, Core\Unit::Minute)->format('HH:mm'), "\n";
// `plus` returns a new time. `$start` does not change, so this prints 10:30.
echo $start->format('HH:mm'), "\n";
Output
11:15
10:30

Past midnight

<?nvs
// Shows that the time goes around the clock when it passes midnight.
Core\Time\TimeOfDay $late = Core\Time\TimeOfDay::at(23, 30);
// This prints 01:30.
echo $late->plus(2, Core\Unit::Hour)->format('HH:mm'), "\n";
// A day is not a unit a time of day can move, so this throws a `LogicError`.
try {
echo $late->plus(1, Core\Unit::Day)->format('HH:mm'), "\n";
} catch (LogicError $e) {
echo $e->message, "\n";
}
Output
01:30
Core\Time\TimeOfDay::plus(): a unit of `Unit::Day` or larger does not move a time of day

A bus timetable

<?nvs
// Prints the departures of a night bus that leaves every 20 minutes.
Core\Time\TimeOfDay $departure = Core\Time\TimeOfDay::at(23, 20);
// This prints 23:20, 23:40, 00:00 and 00:20.
int $i = 0;
while ($i < 4) {
echo $departure->format('HH:mm'), "\n";
$departure = $departure->plus(20, Core\Unit::Minute);
$i = $i + 1;
}
Output
23:20
23:40
00:00
00:20