Unix timestamps in PHP
Everything PHP needs for Unix timestamps: the current epoch time in seconds and milliseconds, timestamp-to-date and date-to-timestamp conversion, and ISO 8601 parsing. PHP's classic trap is date() quietly using the server's date.timezone setting. The '@timestamp' constructor form, by contrast, is always UTC. There's a live converter at the bottom for checking any value the snippets produce.
Get the current Unix timestamp
$seconds = time(); // 1700000000
$millis = (int) round(microtime(true) * 1000); // 1700000000000Convert a timestamp to a date
$dt = new DateTimeImmutable('@1700000000');
echo $dt->format('Y-m-d H:i:s'); // 2023-11-14 22:13:20 (UTC)
echo $dt->setTimezone(new DateTimeZone('Asia/Tokyo'))
->format('Y-m-d H:i:s'); // 2023-11-15 07:13:20The @ constructor always yields UTC regardless of date.timezone; convert zones explicitly with setTimezone().
Convert a date to a timestamp
$seconds = $dt->getTimestamp();
$seconds = strtotime('2023-11-14 22:13:20 UTC');Parse an ISO 8601 string
$dt = new DateTimeImmutable('2023-11-14T22:13:20Z');A string with no zone is read in date.timezone. Prefer DateTimeImmutable over DateTime; mutation bugs in date code are hard to track down.
Check a value
Detected: Unix timestamp (seconds)/t/1700000000
Your timezone
UTC · GMT+00:00 · UTC
Tue, Nov 14, 2023, 10:13:20 PM
Common formats
UTC
Tue, Nov 14, 2023, 10:13:20 PM
ISO 8601
2023-11-14T22:13:20.000Z
Unix (seconds)
1700000000
Unix (millis)
1700000000000
Relative
…
Common questions
- Why do date() and DateTime give different times for the same timestamp?
- date() formats in the configured date.timezone; a DateTime built from '@ts' is UTC until you call setTimezone(). Neither is wrong; they're answering in different zones. Set date.timezone to UTC on servers and convert for display.
- How do I get milliseconds in PHP?
- (int) round(microtime(true) * 1000). time() only has whole-second resolution.
- DateTime or DateTimeImmutable?
- DateTimeImmutable in almost all cases: modifier methods return new objects instead of mutating, so passing a date to a function can't silently change it.