Skip to content

Core\Time\TimeOfDay::with

$timeOfDay->with({…}): Core\Time\TimeOfDay$timeOfDay->with(
    {…},
): Core\Time\TimeOfDay

Returns a copy of a time of day with some of its parts changed.

You name the parts to change: hour, minute, second and nanoseconds (the nanoseconds inside the second). The parts you leave out keep their value. With no parts at all, the result is the same time. The original time does not change.

Each new value must be in the range of its part. The hour is 0 to 23, and the minute and the second are 0 to 59. The nanoseconds are 0 to 999999999. A value outside its range throws a RuntimeError. The time does not move into the next hour or day.

Options

  • houruintoptionalThe new hour, 0 to 23. If you leave it out, the hour stays the same.
  • minuteuintoptionalThe new minute, 0 to 59. If you leave it out, the minute stays the same.
  • seconduintoptionalThe new second, 0 to 59. If you leave it out, the second stays the same.
  • nanosecondsuintoptionalThe new nanoseconds inside the second, 0 to 999999999. If you leave it out, they stay the same.

Return value

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

Errors

  • RuntimeErrorA value is outside its range, for example a minute of 60.

Examples

Change only the hour

<?nvs
// Shows how to change one part of a time and keep the others.
Core\Time\TimeOfDay $alarm = Core\Time\TimeOfDay::at(7, 15);
// Only the hour changes. This prints 08:15.
echo $alarm->with({ hour: 8 })->format('HH:mm'), "\n";
// `with` returns a new time. `$alarm` does not change, so this prints 07:15.
echo $alarm->format('HH:mm'), "\n";
Output
08:15
07:15

A minute out of range

<?nvs
// Shows what happens when a new value is outside the range of its part.
Core\Time\TimeOfDay $t = Core\Time\TimeOfDay::at(10, 30);
// A minute goes from 0 to 59. `with` does not move on to the next hour, so this throws a `RuntimeError`.
try {
echo $t->with({ minute: 60 })->format('HH:mm'), "\n";
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
// Use `plus` to move the time forward instead. This prints 11:00.
echo $t->plus(30, Core\Unit::Minute)->format('HH:mm'), "\n";
Output
Core\Time\TimeOfDay::with(): parameter 'minute' is not in the required range of 0..=59
11:00

Group log lines by hour

<?nvs
// Finds the hour that each log line belongs to, to count the lines per hour.
array<Core\Time\TimeOfDay> $lines = [
Core\Time\TimeOfDay::at(9, 5, { second: 12 }),
Core\Time\TimeOfDay::at(9, 48, { second: 3 }),
Core\Time\TimeOfDay::at(10, 1, { second: 59 }),
];
// Setting the minute and the second to 0 gives the start of the hour.
// This prints 09:00:00 twice, and then 10:00:00.
foreach ($lines as Core\Time\TimeOfDay $line) {
echo $line->with({ minute: 0, second: 0 })->format('HH:mm:ss'), "\n";
}
Output
09:00:00
09:00:00
10:00:00