Skip to content

Core\Time\TimeOfDay::second

$timeOfDay->second(): uint

Returns the second of a time of day, as a uint from 0 to 59.

The second is a whole number. The part of the second after it is returned by nanoseconds. A time made with TimeOfDay::at without a second option has second 0.

The result has the same name and type as the second option of with. So $t->with({ second: 0 }) gives the start of the same minute. The second option must be from 0 to 59, and a value outside that range throws a RuntimeError.

Good to know: $t->hour() * 3600 + $t->minute() * 60 + $t->second() gives the seconds since midnight.

Return value

Returns uint. The second, from 0 to 59.

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 second

<?nvs
// Shows how to read the second of a time of day as a number.
Core\Time\TimeOfDay $lap = Core\Time\TimeOfDay::at(0, 1, { second: 42 });
// `second` returns a `uint` from 0 to 59. This prints 42.
echo $lap->second(), "\n";
// A time made without a `second` option has second 0. This prints 0.
echo Core\Time\TimeOfDay::at(7, 30)->second(), "\n";
Output
42
0

Seconds until the shop closes

<?nvs
// Shows how to count the seconds until a shop closes, for a countdown on its website.
class Countdown
{
public static function secondsOf(Core\Time\TimeOfDay $time): uint
{
return $time->hour() * 3600 + $time->minute() * 60 + $time->second();
}
}
Core\Time\TimeOfDay $closes = Core\Time\TimeOfDay::at(20, 0);
// A real program reads the time from `Core\Time::now()`. A fixed time keeps the output the same.
Core\Time\TimeOfDay $now = Core\Time\TimeOfDay::at(19, 58, { second: 15 });
// There are 1 minute and 45 seconds left. This prints 105.
echo Countdown::secondsOf($closes) - Countdown::secondsOf($now), "\n";
Output
105

Show seconds only when needed

<?nvs
// Shows how to print the seconds of a time only when they are not 0.
class Display
{
public static function show(Core\Time\TimeOfDay $time): string
{
if ($time->second() == 0) {
return $time->format('HH:mm');
}
return $time->format('HH:mm:ss');
}
}
// This prints 08:00 and then 08:00:30.
echo Display::show(Core\Time\TimeOfDay::at(8, 0)), "\n";
echo Display::show(Core\Time\TimeOfDay::at(8, 0, { second: 30 })), "\n";
Output
08:00
08:00:30