PHP timestamps and the timezone trap
PHP keeps an absolute epoch number and a process-wide default timezone in two separate places. Convert a number below, then read how time(), mktime(), strtotime() and DateTimeImmutable split that work — and which ones silently follow the global zone.
UNIX TIMESTAMP INPUT
Date output is floored to milliseconds. Choose a unit explicitly for older dates or values outside auto-detection.
Typical today: 10 (s), 13 (ms), 16 (µs), 19 (ns) digits. A unit heuristic, not a definition. Nnow Ccopy /focus
Local means your device timezone. During a repeated daylight-saving hour, the earlier occurrence is used; use UTC to choose an unambiguous instant.
Browser-side reference calculator. It does not execute Java, Go, PHP or shell commands; use the examples below in your own runtime.
time(), mktime() and strtotime()
The classic trio answers three different questions. All three are affected by the process default timezone except the first one:
| Call | Returns | Follows default timezone? |
|---|---|---|
time() | Integer Unix seconds since 1970-01-01 UTC | No — an epoch count is absolute |
microtime(true) | Float seconds with microsecond fraction | No — same absolute number |
mktime(h, m, s, mo, d, y) | Unix seconds for local calendar fields | Yes — fields are read in the default zone |
strtotime("2023-11-14 00:00:00") | Unix seconds parsed from text | Yes — zone-less text uses the default zone |
date("c", $ts) | Formatted local date-time with offset | Yes |
gmdate("c", $ts) | Formatted UTC date-time | No — always UTC |
That split is the whole trap: date_default_timezone_set("Asia/Shanghai") does not change what time() returns, but it changes what date() prints for the same number, and what mktime() / strtotime() produce from the same text. A value that round-trips correctly in one request can be eight hours off in another worker with a different ini setting.
strtotime, the @ prefix and DateTimeImmutable
@is the escape hatch:strtotime("@1700000000")andnew DateTimeImmutable("@1700000000")treat the digits as an absolute Unix second count and ignore the default timezone entirely. Without@, the same digits are not a valid date string at all.DateTimeImmutableis the safer object API:setTimezone()returns a new value instead of mutating,format("U")gives the epoch seconds as a string, andformat("c")emits ISO 8601 with the zone’s offset.- Epoch parsing: use
new DateTimeImmutable("@1700000000")for whole-second input. WithDateTimeImmutable::createFromFormat, match the input deliberately (Ufor seconds,U.ufor a fractional part), check forfalse, and inspect parsing errors. Do not infer epoch-format behavior from the missing-field rules of calendar formats or assume adding!is a universal fix. - Parsing conventions are not locale detection:
strtotime("11/12/2023")uses the slash-separated American month/day/year convention: November 12. Adding one month to January 31 can normalize into March. Use an explicit format and validate parsed fields for persisted dates.
date_default_timezone_set is process state
- PHP reads
date.timezonefrom php.ini at startup; when it is unset, modern PHP falls back to UTC, not the server’s OS zone.date_default_timezone_get()tells you which one is active. - Setting it inside a library function changes the result for every later
date()/mktime()/strtotime()call in that process — including framework and vendor code. Set it once at bootstrap, or avoid it entirely withDateTimeImmutableplus an explicitDateTimeZone. - DST ambiguity is real: a local wall-clock time during the fall-back hour occurs twice.
mktime()picks one; to get the other, build the value in UTC and convert withsetTimezone(). - 32-bit builds historically capped
time()at 2038; on 64-bit PHP integers are 64-bit andDateTimehandles a much wider range. Store the unit in the column name — the SQL dialects page shows how session time zones change what a database thinks the number means.
Precision, UTC output and other runtimes
- Sub-second precision:
microtime(true)is floating-point wall-clock seconds, not a monotonic timer. Usehrtime()(PHP 7.3+) for elapsed durations. For fractional epoch parsing, pass a correctly formatted decimal string toDateTimeImmutable::createFromFormat("U.u", $text)and check the result instead of relying on float stringification. - UTC text:
gmdate("Y-m-d\TH:i:s\Z", $ts)or(new DateTimeImmutable("@$ts"))->setTimezone(new DateTimeZone("UTC"))->format("c"). For theZsuffix rules see timestamp to ISO 8601. - Same number, different languages: Go time.Unix and Java Instant make the same seconds-vs-milliseconds distinction; Bash date does it at the command line.
ANSWERS
01 How do I convert a Unix timestamp to a date in PHP?
Use date("Y-m-d H:i:s", $ts) for local time or gmdate("Y-m-d H:i:s", $ts) for UTC. Both take an integer Unix second count. For milliseconds, divide by 1,000 first — date() has no millisecond input mode.
02 Does date_default_timezone_set change time()?
No. time() returns an absolute count of seconds since 1970-01-01 UTC, independent of any timezone. The setting changes how date(), mktime() and strtotime() interpret or render local wall-clock time around that number.
03 What is the @ prefix in strtotime("@1700000000")?
It tells PHP the following digits are a Unix timestamp, not a calendar date. The result is absolute and ignores date_default_timezone_set. new DateTimeImmutable("@1700000000") uses the same convention.
04 Why does my PHP date come out eight hours off?
The number is usually correct; the rendering zone is not. date() uses the process default timezone, which may be UTC in CLI and something else under a web SAPI. Compare with gmdate() on the same number and read date_default_timezone_get() before changing any data.
05 Should I use DateTime or DateTimeImmutable?
Prefer DateTimeImmutable. Its setTimezone(), modify() and add() return new objects, so a helper function cannot silently change the caller’s value. DateTime mutates in place, which is a common source of ordering bugs.
06 How do I get the current Unix timestamp with milliseconds in PHP?
time() gives whole seconds and microtime(true) gives a float with a fractional part. For the containing millisecond, use (int) floor(microtime(true) * 1000), subject to floating-point precision and integer range — or take the live four-unit reading on the current Unix time page and compare formats.