Frammenti di timestamp Unix in PHP
Esempi PHP per ottenere secondi Unix, generare millisecondi, formattare timestamp, convertire tra oggetti DateTime e parsare stringhe di data.
PHP timestamp basics
PHP's time() returns whole Unix seconds. Use microtime(true) when you need sub-second precision or want to derive Unix milliseconds for JavaScript-facing APIs.
Formatting dates in PHP
date() formats timestamps in the default server timezone, while gmdate() formats in UTC. For explicit timezone work, use DateTime with DateTimeZone so deployments behave consistently.
PHP production notes
PHP applications often run on shared hosting, containers, or workers with different default timezones. Treat the server default as an implementation detail. Store Unix seconds or UTC DateTime values in persistent data, then choose a DateTimeZone at the point where the timestamp is formatted for a user, report, or integration.
- Use time() for whole Unix seconds in controllers, jobs, and simple scripts
- Use microtime(true) when you need fractional seconds or millisecond precision
- Use gmdate() for stable UTC formatting that ignores the server timezone
- Use DateTimeImmutable for code that should not mutate a date accidentally
Frequently checked PHP details
- Does time() include milliseconds?
- No. time() returns whole Unix seconds. Use microtime(true) if you need fractional seconds or if you need to calculate a millisecond timestamp.
- Why use gmdate() instead of date()?
- gmdate() formats the timestamp in UTC. date() uses the server's configured timezone, which can change between local development, containers, and production hosting.
- How do I check a PHP conversion?
- 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.