Skip to content

Durations and Time

Daniel Carbone edited this page Nov 6, 2026 · 1 revision

Durations and Time

The library uses dcarbone/gotime v2, a port of Go's time.Duration and time.Time.

Durations

Duration fields are stored as DCarbone\Go\Time\Duration. Examples include QueryOptions::$WaitTime, QueryMeta::$RequestTime, SessionEntry::$LockDelay, ACLToken::$ExpirationTTL, HealthCheckDefinition intervals, AutopilotConfiguration thresholds, and several config entry fields (e.g. ServiceResolverConfigEntry::$ConnectTimeout).

Some fields that look like durations are plain Go-duration strings, because they are strings in the Go client. These include AgentServiceCheck::$Interval / $Timeout / $TTL and SessionEntry::$TTL. Pass these as '10s' etc.

Duration constructors and setters accept:

Input Example Meaning
Go duration string '1m30s', '250ms', '2h' parsed
int 2 * Time::Second nanoseconds
float 1.5e9 nanoseconds
\DateInterval new \DateInterval('PT5S') converted
Time\Duration Time::ParseDuration('10s') used as-is
null null zero

An unparseable string throws \InvalidArgumentException (Invalid duration: bogus).

use DCarbone\Go\Time;
use DCarbone\PHPConsulAPI\QueryOptions;

$opts = new QueryOptions(WaitTime: '1m30s');

echo $opts->WaitTime;               // 1m30s
$opts->WaitTime->Seconds();         // 90
$opts->WaitTime->Nanoseconds();     // 90000000000

new QueryOptions(WaitTime: 2 * Time::Second);
new QueryOptions(WaitTime: new \DateInterval('PT5S'));

Useful helpers:

  • Time::ParseDuration('10s') parses a string and throws on bad input.
  • Time::Duration($anything) converts any accepted input.
  • Unit constants: Time::Nanosecond, Microsecond, Millisecond, Second, Minute, Hour.
  • Duration methods: Nanoseconds(), Microseconds(), Milliseconds(), Seconds(), Minutes(), Hours(), Truncate(), Round(), Compare(), DateInterval(), and (string).

When a duration is sent to Consul, it is written in the format the endpoint expects. For example, ?wait= and LockDelay are sent as milliseconds (via PHPLib\dur_to_millisecond()).

Time

Timestamp fields are DCarbone\Go\Time\Time (often nullable). Examples include ACLToken::$CreateTime / $ExpirationTime, CARoot::$NotBefore / $NotAfter, LeafCert::$ValidAfter / $ValidBefore, and ServerHealth::$StableSince. Time\Time extends \DateTime, so the usual format() and comparison operators work.

Consul returns RFC 3339 timestamps, sometimes with fractional seconds. These are parsed by PHPLib\parse_time(), which returns null for empty or unparseable values:

use function DCarbone\PHPConsulAPI\PHPLib\parse_time;

$t = parse_time('2024-01-02T03:04:05.123456Z');
echo $t->format(\DATE_RFC3339_EXTENDED); // 2024-01-02T03:04:05.123+00:00

Upgrading from v3.0

v3.1.0 moved from gotime v1 to v2. If you only pass strings or ints to the library, nothing changes. If you use gotime directly, see the gotime release notes.

Clone this wiki locally