Martin Milo

A blog about software development, architecture, and more.

Weekly updates on latest blog posts, thoughts and useful stuff.

Get UTC timestamp in PHP

php basics

PHP timestamp can be obtained by using DateTime class and specifying the UTC timezone with an instance of DateTimeZone.

This is available since PHP 5.2.0 and as the DateTime __construct() documentation suggests, you should pass first parameter to get the current time. In practice, it looks like this:

// Get date time instance
$dateTime = new \DateTime('now', new \DateTimeZone('UTC'));

print_r($dateTime)
/* 👉️ DateTime Object
(
  [date] => 2022-10-16 13:24:56.702310
  [timezone_type] => 3
  [timezone] => UTC
)
*/

As said, second parameter represents the timezone. In the example above, we passed an instance of DateTimeZone in which we specified UTC as the desired representation of the timezone. If the second parameter (timezone) is omitted or null, the current timezone will be used.

When you pass an instance of DateTimeZone with UTC timezone to the DateTime as second param, you'll always get the same (utc) timestamp no matter the timezone you're currently in.

You may have heard of date() method. The DateTime class supports timezones, so it might be preferable to use it. The DateTime equivalent of date() is DateTime::format.

GMT and UTC share the same current time, so what's the difference between these two?

In a nutshell, GMT is a time zone and UTC is a time standard. In fact, UTC is the standard for time zones worldwide.

When storing the date to the database, you'd want to store it as UTC. You can then convert it in the application layer to any timezone.

Martin Milo
The Author Martin Milo

Seasoned full-stack developer with years of startup experience at Wonderway.io, now focused on BE architecture and DevX at Become1.de. Pragmatic at building own web and native apps. Writing software-related blog posts and teaching.