Skip to content

Core\Time::now

Reads the current time from the system clock and returns it as an Instant. An Instant is one moment, the same everywhere in the world.

An Instant has no time zone. To get a date and a time of day, call ->in($zone) with the zone you want. You can store the moment with toIso or toEpochSeconds and read it back later. To measure how long something takes, use Core\Time::monotonic instead. The system clock can be changed while a program runs, and monotonic cannot.

In a test, #[Test(at: ...)] sets a fixed time, and now returns that time.

The examples below show the current date in a zone, two readings one after the other, and a login session that expires after 30 minutes.

Return value

Returns Core\Time\Instant. The current Instant, to the nanosecond.

Examples

The date in a zone

<?nvs
// Shows how to read the current time and turn it into a date in a zone.
// `Core\Time::now` returns an `Instant`. `toEpochSeconds` gives the seconds
// since 1 January 1970. This prints "after 2024".
var $now = Core\Time::now();
echo $now->toEpochSeconds() >= 1704067200 ? 'after 2024' : 'before 2024', "\n";
// `in` gives the date and time of day in a zone. The text changes every
// minute, so this prints only its length: 16.
string $berlin = $now->in(Core\Time\Zone::of('Europe/Berlin'))->format('yyyy-MM-dd HH:mm');
echo Core\Str::length($berlin), "\n";
Output
after 2024
16

Two readings

<?nvs
// Shows two readings of the clock, one after the other.
var $first = Core\Time::now();
var $second = Core\Time::now();
// `compareTo` returns 0 when both are the same moment and a number above 0
// when `$second` is later. This prints "not earlier".
echo $second->compareTo($first) >= 0 ? 'not earlier' : 'earlier', "\n";
// `since` returns the time between the two as a `Duration`.
// The two calls are very close, so this prints "under one second".
echo $second->since($first)->toMilliseconds() < 1000 ? 'under one second' : 'slow', "\n";
Output
not earlier
under one second

A session that expires

<?nvs
// Shows a login session that is valid for 30 minutes from the moment it starts.
// The program stores the end time as text, for example in a database.
string $stored = Core\Time::now()->plus(30m)->toIso();
// Later, the program reads the stored time back and compares it with the
// current time. This prints "valid".
var $expires = Core\Time\Instant::fromIso($stored);
echo Core\Time::now()->compareTo($expires) < 0 ? 'valid' : 'expired', "\n";
// A session that ended in 2024 is expired. This prints "expired".
var $old = Core\Time\Instant::fromIso('2024-01-01T08:00:00Z');
echo Core\Time::now()->compareTo($old) < 0 ? 'valid' : 'expired', "\n";
// `since` gives the time that is left. This prints "about 30 minutes left".
int $left = $expires->since(Core\Time::now())->toSeconds();
echo $left > 1790 ? 'about 30 minutes left' : 'less time left', "\n";
Output
valid
expired
about 30 minutes left