PHP Unix 時間戳程式碼片段

PHP 範例,用於取得 Unix 秒、產生毫秒、格式化時間戳、在 DateTime 物件之間轉換,以及解析日期字串。

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.