These PHP examples use Unix seconds for the portable baseline and show milliseconds only where the runtime exposes them naturally. The question to answer before copying a snippet is simple: what unit does the next API expect?
Get the current Unix time
$seconds = time();
$milliseconds = (int) floor(microtime(true) * 1000);
Convert a timestamp to UTC
$date = (new DateTimeImmutable("@1700000000"))
->setTimezone(new DateTimeZone("UTC"));
echo $date->format(DateTimeInterface::ATOM);
Production note
The @ prefix creates a Unix-timestamp DateTimeImmutable. Set the display timezone explicitly after construction.
Keep the unit in the field name when a value crosses a boundary: createdAtSeconds and createdAtMs are longer than createdAt, but much less mysterious during an incident.
Frequent questions:
- Q: Does time() include milliseconds?
- A: No. time() returns whole Unix seconds. Use microtime(true) if you need fractional seconds or if you need to calculate a millisecond timestamp.
- Q: Why use gmdate() instead of date()?
- A: gmdate() formats the timestamp in UTC. date() uses the server's configured timezone, which can change between local development, containers, and production hosting.
- Q: How do I check a PHP conversion?
- A: Convert the same value with gmdate('c', $timestamp), then compare it with an independent epoch converter or a database UTC function before using it in a migration.