Skip to content

Core\Time\Date::toIso

$date->toIso(): string

Returns the date as text in the ISO 8601 form YYYY-MM-DD, such as 2026-05-20.

The month and the day always have two digits. The year always has four digits, so the year 5 is written 0005. Year 0 is 0000. A year before year 0 starts with -, such as -0044-03-15.

Core\Time\Date::fromIso reads this text back, and the result is the same date. That makes toIso the right choice when you save a date to a file or a database. ISO text also sorts in date order as a plain string.

Core\Json::encode, Core\Router::url and Core\Uri::buildQuery write a Date as this text. You do not need to call toIso for them.

Good to know: to write a date in another form, such as 20 May 2026, use format.

Return value

Returns string. A string with the year, the month and the day. The year has four digits, and a year before year 0 starts with -. Year 0 is 0000.

Changelog

VersionChange
0.0.6toIso() writes a Date, TimeOfDay or DateTime as ISO 8601 text, such as 2026-01-05 or 08:30:00. A DateTime also writes its offset and time zone: 2026-01-05T08:30:00+01:00[Europe/Vienna]. fromIso reads each text back to an equal value.

Examples

Write a date as iso text

<?nvs
// Shows how to write a date as ISO text, such as `2026-05-20`.
// `toIso` returns the year, the month and the day. This prints 2026-05-20.
var $date = Core\Time\Date::at(2026, 5, 20);
echo $date->toIso(), "\n";
// The year always has four digits. This prints 0005-01-02.
echo Core\Time\Date::at(5, 1, 2)->toIso(), "\n";
// A year before year 0 starts with `-`. This prints -0044-03-15.
echo Core\Time\Date::at(-44, 3, 15)->toIso(), "\n";
Output
2026-05-20
0005-01-02
-0044-03-15

Read the text back

<?nvs
// Shows that `Core\Time\Date::fromIso` reads the text of `toIso` back to the same date.
var $due = Core\Time\Date::at(2024, 2, 29);
string $saved = $due->toIso();
echo $saved, "\n";
// `fromIso` builds a date from the saved text.
// `compareTo` returns 0 for two equal dates, so this prints 0.
var $loaded = Core\Time\Date::fromIso($saved);
echo $loaded->compareTo($due), "\n";
Output
2024-02-29
0

A file name for each day

<?nvs
// Shows how to put a date in a file name, with one file for each day.
var $day = Core\Time\Date::at(2026, 12, 30);
int $i = 0;
while ($i < 3) {
// ISO text has no `/` and sorts in date order, so it is safe in a file name.
echo 'report-', $day->toIso(), ".csv\n";
$day = $day->plus(1, Core\Unit::Day);
$i = $i + 1;
}
Output
report-2026-12-30.csv
report-2026-12-31.csv
report-2027-01-01.csv