メインコンテンツへスキップ

InteractsWithTime とは

Illuminate\Support\InteractsWithTime は、時間・遅延・経過時間の計算をまとめたトレイトです。Laravel フレームワーク内では 40 以上のクラスが use InteractsWithTime; しており、キャッシュ・キュー・コンソール・データベース接続など幅広いコンポーネントで使われています。
ソースコードは src/Illuminate/Support/InteractsWithTime.php にあります。protected メソッドのみで構成されており、クラス内部から呼び出す用途を前提にしています。

フレームワーク内の使用例

クラス利用目的
Cache\ArrayStore / DatabaseStoreTTL(有効期限)の計算
Cache\RateLimiterレート制限のリセット時刻
Queue\Console\RestartCommandワーカー再起動タイムスタンプ
Database\Connectionクエリ実行時間の計測
Console\View\Components\Taskコマンドタスクの実行時間表示
Redis\Limiters\DurationLimiterBuilderRedis レート制限の期間計算

メソッド解説

secondsUntil() — 残り秒数を取得

指定した日時・遅延値までの残り秒数を返します。引数には DateTimeInterfaceDateInterval・秒数の整数値のいずれかを渡せます。
use Illuminate\Support\InteractsWithTime;

class MyService
{
    use InteractsWithTime;

    public function scheduleAt(\DateTime $target): int
    {
        return $this->secondsUntil($target); // 現在から $target までの秒数
    }
}
過去の日時を渡すと 0 を返します(負にはなりません)。
$seconds = $this->secondsUntil(now()->addMinutes(5)); // 300
$seconds = $this->secondsUntil(now()->subMinutes(5)); // 0(過去は 0)
$seconds = $this->secondsUntil(60);                   // 60(整数はそのまま秒数)

availableAt() — 利用可能になる UNIX タイムスタンプ

現在時刻に遅延を加算した UNIX タイムスタンプを返します。キューのジョブ遅延やキャッシュの有効期限計算に使われます。
$timestamp = $this->availableAt(60);              // 60 秒後の UNIX タイムスタンプ
$timestamp = $this->availableAt(new \DateTime('2026-12-31')); // 指定日時の UNIX タイムスタンプ
$timestamp = $this->availableAt(new \DateInterval('PT5M'));    // 5 分後
引数なし(デフォルト 0)で呼ぶと現在時刻のタイムスタンプを返します。

parseDateInterval() — DateInterval を DateTime に変換

DateInterval インスタンスを受け取ると、現在時刻に加算した Carbon インスタンスに変換して返します。DateTimeInterface や整数値はそのまま返します。
$delay = $this->parseDateInterval(new \DateInterval('P1D')); // 明日の Carbon
$delay = $this->parseDateInterval(now()->addHour());         // DateTimeInterface はそのまま
$delay = $this->parseDateInterval(3600);                     // 3600(整数はそのまま)
secondsUntil()availableAt() は内部でこのメソッドを呼んでいます。

currentTime() — 現在時刻の UNIX タイムスタンプ

Carbon::now()->getTimestamp() を返すシンプルなラッパーです。secondsUntil() の基準時刻として使われます。
$now = $this->currentTime(); // int(UNIX タイムスタンプ)

runTimeForHumans() — 実行時間を人間が読みやすい形式に

microtime(true) で記録した開始時刻と終了時刻の差を、読みやすい文字列に変換します。
$start = microtime(true);

// ... 処理 ...

echo $this->runTimeForHumans($start); // 例: "42.15ms" または "1s 234ms"
1000ms 未満は 42.15ms のように小数点付きミリ秒、1000ms 以上は CarbonInterval の forHumans() 短縮形式(1s 234ms など)で返します。 第2引数に終了時刻を渡すことで、計測済みの区間を変換することもできます。
$elapsed = $this->runTimeForHumans($start, $end);

パッケージ開発での活用

キャッシュドライバーの TTL 統一

put(key, value, ttl)ttl として intDateIntervalDateTime のいずれも受け付けるメソッドを作るときに便利です。
use Illuminate\Support\InteractsWithTime;

class MyStore
{
    use InteractsWithTime;

    public function put(string $key, mixed $value, mixed $ttl): void
    {
        $seconds = $this->secondsUntil($ttl);

        // $seconds(int)で実際のストレージに保存
        $this->storage[$key] = [
            'value'      => $value,
            'expires_at' => $this->availableAt($ttl),
        ];
    }
}

コンソールコマンドの処理時間表示

Artisan コマンドの handle() で処理時間をユーザーに表示する際に活用できます。
use Illuminate\Console\Command;
use Illuminate\Support\InteractsWithTime;

class ProcessDataCommand extends Command
{
    use InteractsWithTime;

    public function handle(): void
    {
        $start = microtime(true);

        // ... 処理 ...

        $this->info("完了: {$this->runTimeForHumans($start)}");
    }
}

テスト用の InteractsWithTime

Illuminate\Foundation\Testing\Concerns\InteractsWithTime は別物で、テストケースで時間を操作する travel*() メソッドを提供します(TestCase に自動的に組み込まれます)。
// テスト内で時間を進める(Testing\Concerns\InteractsWithTime)
$this->travel(5)->days();
$this->travelTo(now()->addMonth());
$this->travelBack();
Illuminate\Support\InteractsWithTime(本ページの対象)とは名前空間が異なるため、混同しないよう注意してください。

まとめ

メソッド戻り値主な用途
secondsUntil($delay)int残り秒数の取得
availableAt($delay)int有効開始タイムスタンプの計算
parseDateInterval($delay)DateTimeInterface|intDateInterval → Carbon への変換
currentTime()int現在の UNIX タイムスタンプ
runTimeForHumans($start, $end)string実行時間の人間向け表示
引数に intDateIntervalDateTimeInterface のいずれも受け付けるメソッドを作りたい場合、このトレイトを use するだけで変換ロジックを再実装せずに済みます。

関連ページ

最終更新日 2026年7月12日