Core\Time\Date::format
Converts a date to text, in the layout that a pattern describes.
The pattern is a string of letters, and each group of letters is one part of the date. yyyy is the year, MM is the month with two digits and dd is the day with two digits. MMMM is the name of the month and EEEE is the name of the weekday. Text inside single quotes is copied to the result unchanged.
A date has no time of day and no time zone. A pattern with a letter for a time, such as HH, throws a LogicError. A pattern that is not written correctly throws a LogicError too.
Good to know: Core\Time\DateTime::format reads the same letters, and it also has the letters for a time of day.
Parameters
$patternstringA CLDR pattern with date letters only. A pattern is a small language, so ataintedpattern is not allowed.
Return value
Returns string. The rendered text.
Errors
LogicError$patternis not valid, or has a time-of-day or zone letter. A date has no time of day and no zone.
Examples
Dates in common layouts
<?nvs// Shows how to write one date in three common layouts.
var $date = Core\Time\Date::at(2024, 4, 5);
// `yyyy` is the year, `MM` the month and `dd` the day, each with leading zeros.// This prints 2024-04-05.echo $date->format('yyyy-MM-dd'), "\n";
// The same fields in another order, with dots. This prints 05.04.2024.echo $date->format('dd.MM.yyyy'), "\n";
// `EEEE` is the name of the weekday and `MMMM` the name of the month.// One `d` has no leading zero. This prints Friday, 5 April 2024.echo $date->format('EEEE, d MMMM yyyy'), "\n";2024-04-0505.04.2024Friday, 5 April 2024Text and a time of day
<?nvs// Shows how to put plain text in a pattern, and what happens when a pattern asks for a time.
var $date = Core\Time\Date::at(2024, 11, 20);
// Text inside single quotes is printed as it is. `Q` is the quarter of the year.// This prints Quarter 4 of 2024.echo $date->format("'Quarter' Q 'of' yyyy"), "\n";
// A date has no time of day, so `HH` and `mm` throw a `LogicError`.try { echo $date->format('yyyy-MM-dd HH:mm'), "\n";} catch (LogicError $error) { echo 'Not allowed: ', $error->message, "\n";}Quarter 4 of 2024Not allowed: Core\Time\Date::format(): a pattern rendering a date names no time of day — a `Core\Time\Date` carries noneMonthly export file names
<?nvs// Shows how to build the file name of a monthly sales export from a date.
// The quoted parts are fixed text, and `yyyy-MM` is the year and the month.// Names in this form sort in the order of the months.var $month = Core\Time\Date::at(2024, 10, 1);int $i = 0;while ($i < 4) { echo $month->format("'sales-'yyyy-MM'.csv'"), "\n"; $month = $month->plus(1, Core\Unit::Month); $i = $i + 1;}sales-2024-10.csvsales-2024-11.csvsales-2024-12.csvsales-2025-01.csv