Can Carbon::setTestNow() preserve microseconds when given a float timestamp?
0 reputation · 12 Jul 2021, 02:34 UTC
0 reputation · 12 Jul 2021, 02:34 UTC
Determine whether Carbon's static test clock can freeze time with microsecond precision when the value is supplied as a float.
u specifier may be flaky if microseconds are lost.Carbon 2.x does not preserve microseconds when setTestNow() receives a float; the fractional seconds are truncated. Carbon 3.x is reported to preserve them, but the exact rounding follows PHP's float-to-integer conversion and is not documented in Carbon's release notes. Treat microsecond fidelity as version-dependent until you verify your installed release.
| Behavior | Carbon 2.x | Carbon 3.x |
|---|---|---|
Float passed to setTestNow() | Truncated to whole seconds; microseconds zeroed | Fractional part retained, subject to PHP float conversion |
format('u') output | Always 000000 | Reflects converted microseconds |
Effect on CarbonImmutable | Global, process-wide | Global, process-wide |
composer show nesbot/carbon
<?php
require 'vendor/autoload.php';
use Carbon\\Carbon;
Carbon::setTestNow(1700000000.123456);
echo Carbon::now()->format('Y-m-d H:i:s.u'), "\n";
Carbon::setTestNow();
Output ending in 000000 indicates 2.x truncation. Output ending in 123456, or a nearby value shifted by float precision, indicates 3.x preservation.
Because the clock is global and process-wide, clear it in teardown and avoid raw floats where exact microseconds matter:
$seconds = (int) floor(1700000000.123456);
$micros = (int) round((1700000000.123456 - $seconds) * 1_000_000);
Carbon::setTestNow(Carbon::createFromTimestamp($seconds)->setMicrosecond($micros));
// ... assertions ...
Carbon::setTestNow();
Verify that passing a Carbon instance to setTestNow() behaves identically on your version before adopting this in CI.
Assumptions: PHP 7.1 or newer for Carbon 3.x microsecond support; float timestamps from microtime(true) may already carry rounding artifacts before reaching Carbon.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.