Core\Time\Instant::toIso
$instant->toIso(): stringReturns this instant as text in the RFC 3339 format, always in UTC.
The text looks like 2024-03-01T12:00:00Z. The Z at the end means UTC. Most JSON and HTTP APIs expect dates in this format, and Core\Time\Instant::fromIso reads it back into the same instant. The seconds have a fraction only when the fraction is not zero. For example, half a second past noon is written 12:00:00.5Z.
The year always has four digits. A year before year 0 has a - in front, so the earliest instant is written -9999-01-02T01:59:59Z.
An instant has no time zone, so the text is the same wherever the program runs. To show the time on a local clock, use in with a Zone first.
Return value
Returns string. A string such as 2024-03-01T12:00:00Z. It has a fraction of a second only when the fraction is not zero.
Changelog
| Version | Change |
|---|---|
0.0.6 | Instant::toIso writes a year before year 1 with four digits, such as -9999-01-02T01:59:59Z. Instant::fromIso reads this text back. JSON reads an Instant with the same rules as Instant::fromIso. |
Examples
An instant as text
<?nvs// Shows how to write an instant as text.
// `fromEpoch` takes the seconds since 1 January 1970. This prints 2024-03-01T12:00:00Z.echo Core\Time\Instant::fromEpoch(1709294400)->toIso(), "\n";
// A fraction of a second is written only when it is not zero. This prints 2024-03-01T12:00:00.25Z.echo Core\Time\Instant::fromEpoch(1709294400)->plus(250ms)->toIso(), "\n";2024-03-01T12:00:00Z2024-03-01T12:00:00.25ZThe text is always utc
<?nvs// Shows that `toIso` always writes the time in UTC, whatever offset the input had.
// 13:00 in a zone one hour ahead of UTC is 12:00 in UTC. This prints 2024-03-01T12:00:00Z.echo Core\Time\Instant::fromIso('2024-03-01T13:00:00+01:00')->toIso(), "\n";
// `fromIso` reads the text back, and the result is the same instant. This prints 0.Core\Time\Instant $at = Core\Time\Instant::fromIso('2024-03-01T07:30:00-04:30');echo Core\Time\Instant::fromIso($at->toIso())->compareTo($at), "\n";2024-03-01T12:00:00Z0A date in a json reply
<?nvs// Puts the time an order was placed into a JSON reply, as an API does.
// A real program uses `Core\Time::now()` here. A fixed time keeps the output the same.Core\Time\Instant $placed = Core\Time\Instant::fromEpoch(1709294400);
// This prints {"order":"A-1001","placedAt":"2024-03-01T12:00:00Z"}.echo Core\Json::encode(['order' => 'A-1001', 'placedAt' => $placed->toIso()]), "\n";{"order":"A-1001","placedAt":"2024-03-01T12:00:00Z"}