Skip to content

Core\Time\DateTime::toInstant

$dateTime->toInstant(): Core\Time\Instant

Returns the exact moment of a date and time, as a Core\Time\Instant.

A date and time is a local time in one time zone, such as 14:30 in Vienna. An Instant is a point in time that is the same everywhere, and it has no time zone. toInstant gives that point. 14:30 in Vienna on 1 July 2024 is 12:30 in UTC.

Use it to compare values from different time zones. 09:00 in London and 18:00 in Tokyo on 15 January 2024 are the same moment, so their instants are equal. Use it also to measure the real time between two values, such as how long a flight takes.

In plain words: the local time is what a clock on the wall shows in one city. The instant is the moment itself, and it is the same moment in every city.

Return value

Returns Core\Time\Instant. The Instant. It has no zone.

Examples

The moment in utc

<?nvs
// Shows how to get the exact moment of a local date and time, without its time zone.
var $vienna = Core\Time\Zone::of('Europe/Vienna');
var $meeting = Core\Time\DateTime::fromIso('2024-07-01 14:30', $vienna);
// `toInstant` returns the moment as an `Instant`. An `Instant` has no time zone.
// `toIso` writes it in UTC. Vienna is 2 hours ahead in summer, so this prints 2024-07-01T12:30:00Z.
echo $meeting->toInstant()->toIso(), "\n";
// The number of seconds since 1 January 1970, UTC. This prints 1719837000.
echo $meeting->toInstant()->toEpochSeconds(), "\n";
Output
2024-07-01T12:30:00Z
1719837000

The same moment in two places

<?nvs
// Shows how to check whether two local times in different time zones are the same moment.
var $london = Core\Time\DateTime::fromIso('2024-01-15 09:00', 'Europe/London');
var $tokyo = Core\Time\DateTime::fromIso('2024-01-15 18:00', 'Asia/Tokyo');
var $newYork = Core\Time\DateTime::fromIso('2024-01-15 09:00', 'America/New_York');
// 9:00 in London is 18:00 in Tokyo, so `compareTo` returns 0.
echo $london->toInstant()->compareTo($tokyo->toInstant()), "\n";
// 9:00 in New York is 5 hours after 9:00 in London. `since` returns the time between them.
// This prints 18000, the number of seconds in 5 hours.
echo $newYork->toInstant()->since($london->toInstant())->toSeconds(), "\n";
Output
0
18000

How long a flight takes

<?nvs
// Shows how to work out how long a flight takes when it lands in another time zone.
// A timetable shows local times: departure in Vienna, arrival in New York.
var $departs = Core\Time\DateTime::fromIso('2024-06-10 10:15', 'Europe/Vienna');
var $lands = Core\Time\DateTime::fromIso('2024-06-10 13:05', 'America/New_York');
// `toInstant` gives the exact moment of each local time. `since` returns the time between them.
// This prints 530, the length of the flight in minutes.
var $flight = $lands->toInstant()->since($departs->toInstant());
echo $flight->toSeconds() / 60, "\n";
Output
530