Core\Time\TimeOfDay::format
Returns the time of day as text, in a pattern you choose.
The pattern uses letters for the parts of the time. HH is the hour from 00 to 23, h is the hour from 1 to 12, mm is the minute and ss is the second. a is AM or PM, and SSS shows milliseconds. Any other text in the pattern goes into the result as it is. The letters are the same ones DateTime::format uses.
A TimeOfDay has no date and no time zone. So a pattern with a letter for the year, the day or the zone throws a LogicError. The pattern must come from your program: a tainted pattern (text that came from a request or another outside source) does not compile.
Parameters
$patternstringThe pattern, such asHH:mm. It may use letters for the hour, the minute, the second, parts of a second and AM or PM. Ataintedpattern (text from outside the program) is not allowed.
Return value
Returns string. The time as text.
Errors
LogicError$patternis not a valid pattern, or it uses a letter for a date or a time zone.
Examples
A 24 hour and a 12 hour clock
<?nvs// Shows the same time as text on a 24-hour clock and on a 12-hour clock.
Core\Time\TimeOfDay $evening = Core\Time\TimeOfDay::at(21, 5);
// `HH` is the hour from 00 to 23. This prints 21:05.echo $evening->format('HH:mm'), "\n";
// `h` is the hour from 1 to 12, and `a` is AM or PM. This prints 9:05 PM.echo $evening->format('h:mm a'), "\n";21:059:05 PMA letter for a date
<?nvs// Shows what happens when the pattern asks for a part that a time of day does not have.
Core\Time\TimeOfDay $start = Core\Time\TimeOfDay::at(8, 15);
// `yyyy` is the year. A `TimeOfDay` has no date, so `format` throws a `LogicError`.try { echo $start->format('yyyy HH:mm'), "\n";} catch (LogicError $e) { echo $e->message, "\n";}
// Text in single quotes is copied as it is. This prints "starts at 08:15".echo $start->format("'starts at' HH:mm"), "\n";Core\Time\TimeOfDay::format(): a pattern rendering a time of day names no calendar field — a `Core\Time\TimeOfDay` carries nonestarts at 08:15Timestamps in a log
<?nvs// Writes the time in front of each line of a log, with milliseconds.
Core\Time\TimeOfDay $at = Core\Time\TimeOfDay::at(14, 2, { second: 9, nanoseconds: 120000000 });array<string> $events = ['request received', 'database query done', 'response sent'];
foreach ($events as string $event) { // `SSS` is the milliseconds. The first line starts with 14:02:09.120. echo '[', $at->format('HH:mm:ss.SSS'), '] ', $event, "\n"; $at = $at->plus(35, Core\Unit::Millisecond);}[14:02:09.120] request received[14:02:09.155] database query done[14:02:09.190] response sent