PHP code example of phpnomad / chrono

1. Go to this page and download the library: Download phpnomad/chrono library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpnomad / chrono example snippets


use DateTimeImmutable;
use PHPNomad\Chrono\Interfaces\CanCheckIfPast;
use PHPNomad\Chrono\Interfaces\ClockStrategy;

final class TokenService
{
    public function __construct(
        private ClockStrategy $clock,
        private CanCheckIfPast $past,
    ) {}

    public function isExpired(DateTimeImmutable $expiresAt): bool
    {
        return $this->past->isPast($expiresAt);
    }

    public function issueExpiringIn(string $relative): DateTimeImmutable
    {
        return $this->clock->now()->modify($relative);
    }
}

$clock = new Lcobucci\Clock\FrozenClock(new DateTimeImmutable('2026-05-27T12:00:00Z'));
$past  = new class ($clock) implements CanCheckIfPast {
    public function __construct(private ClockStrategy $clock) {}
    public function isPast(DateTimeImmutable $i): bool { return $i < $this->clock->now(); }
};
$service = new TokenService($clock, $past);

$this->assertFalse($service->isExpired(new DateTimeImmutable('2026-05-27T13:00:00Z')));
$this->assertTrue($service->isExpired(new DateTimeImmutable('2026-05-27T11:00:00Z')));

class WordPressClockStrategy implements
    ClockStrategy,
    HasTimezone,
    CanFormatLocalizedDate,
    CanFormatRelativeTime
{
    public function now(): DateTimeImmutable { /* current_datetime() */ }
    public function getTimezone(): DateTimeZone { /* wp_timezone() */ }
    public function formatLocalized(DateTimeImmutable $i, string $f): string { /* wp_date() */ }
    public function relative(DateTimeImmutable $i): string { /* human_time_diff() */ }
}