Skip to content

Core\Time\TimeOfDay::hour

$timeOfDay->hour(): uint

Returns the hour of a time of day, as a uint from 0 to 23.

Midnight is 0, noon is 12 and 23:59 has hour 23. The value is the same number you give to TimeOfDay::at as the first argument.

The result has the same name and type as the hour option of with. So $t->with({ hour: 8 }) gives the same minutes and seconds at 8 o'clock. The hour option must be from 0 to 23, and a value outside that range throws a RuntimeError.

Good to know: to move the time forward and wrap past midnight, use plus(1, Core\Unit::Hour). $t->with({ hour: $t->hour() + 1 }) throws a RuntimeError at hour 23.

Return value

Returns uint. The hour, from 0 to 23.

Changelog

VersionChange
0.0.5Core\Time\TimeOfDay::hour, Core\Time\TimeOfDay::minute, Core\Time\TimeOfDay::second and Core\Time\TimeOfDay::nanoseconds return the parts of a time as numbers. Each one returns a uint.

Examples

Read the hour

<?nvs
// Shows how to read the hour of a time of day as a number.
Core\Time\TimeOfDay $closes = Core\Time\TimeOfDay::at(18, 30);
// `hour` returns a `uint` from 0 to 23. This prints 18.
echo $closes->hour(), "\n";
// The last hour before midnight is 23. This prints 23.
echo Core\Time\TimeOfDay::at(23, 59)->hour(), "\n";
Output
18
23

A 12 hour clock

<?nvs
// Shows how to turn the hour into a 12-hour clock with AM and PM.
class TwelveHour
{
public static function show(Core\Time\TimeOfDay $time): string
{
uint $hour = $time->hour() % 12;
// Midnight and noon are 12 on a 12-hour clock, not 0.
if ($hour == 0) {
$hour = 12;
}
string $half = $time->hour() < 12 ? 'AM' : 'PM';
return $hour . ' ' . $half;
}
}
// This prints 12 AM, 9 AM, 12 PM and 7 PM.
array<uint> $hours = [0, 9, 12, 19];
foreach ($hours as uint $h) {
echo TwelveHour::show(Core\Time\TimeOfDay::at($h, 0)), "\n";
}
// `format` with `h a` gives the same result. This prints 7 PM.
echo Core\Time\TimeOfDay::at(19, 0)->format('h a'), "\n";
Output
12 AM
9 AM
12 PM
7 PM
7 PM

The night rate

<?nvs
// Shows how to choose a taxi rate from the hour: the night rate is from 22:00 to 06:00.
class Taxi
{
public static function rate(Core\Time\TimeOfDay $pickup): string
{
uint $hour = $pickup->hour();
// The night goes past midnight, so it is two ranges: from 22 to 23, and from 0 to 5.
if ($hour >= 22 || $hour < 6) {
return 'night';
}
return 'day';
}
}
// This prints day, night, night and day.
echo Taxi::rate(Core\Time\TimeOfDay::at(21, 59)), "\n";
echo Taxi::rate(Core\Time\TimeOfDay::at(22, 0)), "\n";
echo Taxi::rate(Core\Time\TimeOfDay::at(5, 45)), "\n";
echo Taxi::rate(Core\Time\TimeOfDay::at(6, 0)), "\n";
Output
day
night
night
day