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.

[MOD.CONV // INSTRUMENT]

UNIX TIMESTAMP INPUT

Auto-detects seconds, ms, µs, ns

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.

01 Local time —
02 UTC standard —
03 ISO 8601 —
04 Relative —
[SUB.REVERSE]
SECONDS (S) —
MILLISECONDS (MS) —

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.

[SEC.02 // THE THREE FUNCTIONS]

time(), mktime() and strtotime()

NUMBER IN / TEXT OUT

The classic trio answers three different questions. All three are affected by the process default timezone except the first one:

CallReturnsFollows default timezone?
time()Integer Unix seconds since 1970-01-01 UTCNo — an epoch count is absolute
microtime(true)Float seconds with microsecond fractionNo — same absolute number
mktime(h, m, s, mo, d, y)Unix seconds for local calendar fieldsYes — fields are read in the default zone
strtotime("2023-11-14 00:00:00")Unix seconds parsed from textYes — zone-less text uses the default zone
date("c", $ts)Formatted local date-time with offsetYes
gmdate("c", $ts)Formatted UTC date-timeNo — 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.

[SEC.03 // PARSE BACK SAFELY]

strtotime, the @ prefix and DateTimeImmutable

ABSOLUTE VS LOCAL TEXT
  • @ is the escape hatch: strtotime("@1700000000") and new 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.
  • DateTimeImmutable is the safer object API: setTimezone() returns a new value instead of mutating, format("U") gives the epoch seconds as a string, and format("c") emits ISO 8601 with the zone’s offset.
  • Epoch parsing: use new DateTimeImmutable("@1700000000") for whole-second input. With DateTimeImmutable::createFromFormat, match the input deliberately (U for seconds, U.u for a fractional part), check for false, 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.
[SEC.04 // THE GLOBAL ZONE]

date_default_timezone_set is process state

ONE SETTING, ALL CALLERS
  • PHP reads date.timezone from 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 with DateTimeImmutable plus an explicit DateTimeZone.
  • 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 with setTimezone().
  • 32-bit builds historically capped time() at 2038; on 64-bit PHP integers are 64-bit and DateTime handles 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.
[SEC.05 // CROSS-CHECK]

Precision, UTC output and other runtimes

SAME INSTANT, MANY VIEWS
  • Sub-second precision: microtime(true) is floating-point wall-clock seconds, not a monotonic timer. Use hrtime() (PHP 7.3+) for elapsed durations. For fractional epoch parsing, pass a correctly formatted decimal string to DateTimeImmutable::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 the Z suffix 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.
[DOC.FAQ // INDEX]

ANSWERS

06 ITEMS
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.

[SEC.MATRIX // RELATED]

Related tools

3 PAGES

Sources and specifications