Get UTC timestamp in PHP
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.