Unix timestamps in PHP

PHP works in whole seconds and makes timestamps easy. What changes results between servers is the default time zone that date() and strtotime() silently use.

Current timestamp

echo time();                              // e.g. 1763164800     seconds
echo (int) (microtime(true) * 1000);      // e.g. 1763164800123  milliseconds
echo hrtime(true);                        // nanoseconds from an arbitrary point: for timing code, not for dates

Timestamp to date

Every example uses 1700000000, which is 14 November 2023 at 22:13:20 UTC, so you can compare the output across languages or check it in the timestamp converter.

echo gmdate('Y-m-d\TH:i:s\Z', 1700000000);     // 2023-11-14T22:13:20Z   always UTC
echo date('Y-m-d H:i:s', 1700000000);          // in the default time zone (date.timezone)

$d = (new DateTimeImmutable('@1700000000'))->setTimezone(new DateTimeZone('America/New_York'));
echo $d->format('Y-m-d H:i:s T');              // 2023-11-14 17:13:20 EST
echo $d->format(DATE_ATOM);                    // 2023-11-14T17:13:20-05:00

A leading @ tells DateTime the string is a Unix timestamp. An object made that way is in UTC whatever the default zone is, so call setTimezone before formatting it for people.

Date to timestamp

echo strtotime('2023-11-14 22:13:20 UTC');     // 1700000000
echo strtotime('2023-11-14T17:13:20-05:00');   // 1700000000
echo gmmktime(22, 13, 20, 11, 14, 2023);       // 1700000000   hour, minute, second, month, day, year

$d = new DateTimeImmutable('2023-11-14 22:13:20', new DateTimeZone('UTC'));
echo $d->getTimestamp();                       // 1700000000

mktime() is the same as gmmktime() but reads its arguments in the default time zone.

Pitfalls

  • The default time zone. date(), mktime() and strtotime() on a string with no zone all use date.timezone from php.ini, or whatever date_default_timezone_set() last set. Use gmdate(), or name the zone.
  • strtotime() returns false when it cannot read the string, and false turns into 0, which is 1 January 1970. Check the result.
  • Slashes and dashes. strtotime('03/04/2024') is read as month/day (4 March) and '03-04-2024' as day-month (3 April). Use Y-m-d, or DateTimeImmutable::createFromFormat() with the exact format.
  • On a 64-bit build, integers are 64-bit and there is no 2038 limit. A 32-bit build stops at 2,147,483,647.

Questions

How do I get the current timestamp in PHP?

time() returns the current Unix timestamp in seconds. For milliseconds use (int) (microtime(true) * 1000).

What is the difference between date() and gmdate()?

They take the same format string and timestamp. date() formats in the default time zone set in php.ini or by date_default_timezone_set(); gmdate() always formats in UTC.

Why does my PHP date show 1970-01-01?

The timestamp passed to date() was 0, false or null, usually because strtotime() failed to parse its input. Check for false before formatting.