Both gmdate() and date() can format timestamps into readable time strings, but there is one key difference:
gmdate() is based on Greenwich Standard Time (GMT/UTC) and does not consider time zone offset.
date() will format the time according to the default time zone configured by PHP (or the time zone set by date_default_timezone_set() ).
For example:
echo gmdate('Y-m-d H:i:s', time()); // Output:2025-05-25 08:00:00(UTCtime)
echo date('Y-m-d H:i:s', time()); // Output:2025-05-25 16:00:00(Assume that the time zone is Asia/Shanghai)
In some businesses, we need to make precise conversions between time zone time and UTC time, especially in multinational business systems, where UTC is used to store data uniformly and display it in local time. At this time, the coordination between gmdate() and date() becomes particularly important.
Assuming that the user enters "2025-05-25 16:00:00", we need to convert it to a UTC timestamp for storage:
date_default_timezone_set('Asia/Shanghai');
$local_time = '2025-05-25 16:00:00';
$timestamp = strtotime($local_time); // 本地time的time戳
$utc_time = gmdate('Y-m-d H:i:s', $timestamp);
echo $utc_time; // Output:2025-05-25 08:00:00
If we need to send this UTC time to the API:
$url = 'https://gitbox.net/api/sync?time=' . urlencode($utc_time);
Assuming that the time read from the database is in UTC format, we want to show the time as the time zone where the user is located:
date_default_timezone_set('Asia/Shanghai');
$utc_timestamp = strtotime('2025-05-25 08:00:00');
$local_time = date('Y-m-d H:i:s', $utc_timestamp);
echo $local_time; // Output:2025-05-25 16:00:00
This method is suitable for log display, timeline display and other functions.
When you develop a distributed system, you can use gmdate() to ensure consistency of all time data. For example, logging server logs:
$log = '[' . gmdate('Y-m-d H:i:s') . '] Task started' . PHP_EOL;
file_put_contents('/var/logs/task.log', $log, FILE_APPEND);
All servers can be aligned regardless of the time zone in which they are in.
If you need to get a certain day's UTC zero-point timestamp (commonly used for statistical tasks):
date_default_timezone_set('UTC');
$timestamp = strtotime('2025-05-25 00:00:00');
echo $timestamp; // Output:1748131200
If you want to construct an API request:
$url = 'https://gitbox.net/report?start=' . $timestamp;
Always clarify the current time zone settings and use date_default_timezone_get() to view the current time zone.
Before using gmdate() and date(), you must be clear about the semantics of the target time: is it the user's local time or the system's unified time?
It is recommended to use date() for user-visible times, and use gmdate() for internal storage or synchronization of the system.